Jump to content

Chained combobox filteration


PhP-Freak

Recommended Posts

Hello everybody,

I want to make a chained (combo box/drop list) filtration based on previous combo box selection.

I attached an example, kindly take a look in it, it does:

you select a country (US for example) in the first combo box, it filters the second one to shows only US states, if you choose France, it will show only France states ... and so on. and it works very well.

 

I have 2 questions:

- After the filtration, the first combo box returns to the first value (All) I need it to stick to the selected value.

- I want to make a 3rd combo box to be filtered based on 2nd combo box, i.e: for cities selection for example

- If I am to insert the final selection into the data base, how would I do so?? I can only select but don't know how to insert

 

 

Any input here is very appreciated, I really need it

Thanks

 

[attachment deleted by admin]

Link to comment
https://forums.phpfreaks.com/topic/160441-chained-combobox-filteration/
Share on other sites

it just happened to be free ;)

I have 2 files:

 

index.php

<?include("config.php");?>
<form name="form" action="" method="GET" name="form">
<select onchange="document.form.submit()" name="sel">
<?
$sql = "select * from master order by id";
$rs = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($rs) > 0 ){
while($row = mysql_fetch_array($rs,MYSQL_ASSOC)){
	?>
	<option value="<?=$row['id']?>"><?=$row['master']?></option>
	<?}}

	?>
<input type="hidden">
</select>
<br><br><br>
<select>
<?
if ($_GET[sel]==""){$sql = "select * from part";}
else{$sql = "select * from part where id_master='$_GET[sel]'";}

$rs = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($rs) > 0 ){
while($row = mysql_fetch_array($rs,MYSQL_ASSOC)){
	?>
	<option><?=$row['sub']?></option>
	<?}}

			?>
</select>
</form>

 

 

config.php

<?php
$domin =  "http:/localhost/category";
$host = "localhost";
$user_name ="root";
$password = "";
$db_name = "combo";
$con = mysql_connect($host,$user_name,$password)or die (mysql_error());
mysql_select_db($db_name)or die (mysql_error());
?>

 

 

Database:

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `combo`
--

-- --------------------------------------------------------

--
-- Table structure for table `master`
--

CREATE TABLE IF NOT EXISTS `master` (
  `id` int(20) NOT NULL auto_increment,
  `master` varchar(20) character set utf8 collate utf8_unicode_ci NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

--
-- Dumping data for table `master`
--

INSERT INTO `master` (`id`, `master`) VALUES
(5, 'Germany'),
(4, 'France'),
(3, 'UK'),
(2, 'US'),
(1, 'All');

-- --------------------------------------------------------

--
-- Table structure for table `part`
--

CREATE TABLE IF NOT EXISTS `part` (
  `id_master` int(11) NOT NULL,
  `sub` varchar(20) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `part`
--

INSERT INTO `part` (`id_master`, `sub`) VALUES
(2, 'Alabama'),
(2, 'Arizona'),
(2, 'California'),
(5, 'Berlin'),
(5, 'Hamburg'),
(5, 'Bremen'),
(4, 'Paris'),
(4, 'Caen');

I would use ajax.

 

I haven't used any of your existing code - you can change that  ;D

 

file containing the select tags

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="_javascript/jx.js"></script> 
<script type="text/javascript">
<!--
function setOptions(parent,element,table,field, parameter) {
var pval = document.getElementById(parent).value;	

jx.load('_ajax/setOptions.php', 'element='+element+'&table='+table+'&parameter='+parameter+'&field='+field+'&value='+pval, 'POST', function(data){
		eval(data);	
});		
}
//-->
</script>
</head>

<body>

<form name="testform" action="" method="post">
<select name="s1" id="s1" onchange="setOptions('s1','s2','tbl_data','field','parameter');">
<option value="test">test</option>
<option value="test1">test1</option>
</select>
<select name="s2" id="s2" onchange="setOptions('s2','s3','tbl_data','field','parameter');"></select>
<select name="s3" id="s3"></select>
</form>

</body>
</html>

 

 

the file called by ajax (setOptions.php)

<?php
//remove options from select
echo "var el = document.getElementById('".$_POST['element']."');";
echo "el.options.length = 0;";

//select data from database here.
//something like:

$query = "SELECT ".$_POST['field']." FROM ".$_POST['table']." WHERE ".$_POST['parameter']."=".$_POST['value'];
$result = mysql_query($query);

while($row=mysql_fetch_array($result)) {
	//get element to add to
	echo "var el = document.getElementById('".$_POST['element']."');";	
	//create option
	echo "var objOption = document.createElement('option');";
	//add text
	echo "objOption.text = '".$row[$_POST['field']]."';";
	//add value
	echo "objOption.value = '".$row[$_POST['field']]."';";
	//add to element
		echo "el.add(objOption, 0);";
}	

?>

 

the ajax file itself (jx.js)

//V3.00.A - http://www.openjs.com/scripts/jx/
//Alterered by andrew green 15/2/2007
jx = {
http:false, //HTTP Object
format:'text',
callback:function(data){},
error:false,
//Create a xmlHttpRequest object - this is the constructor. 
getHTTPObject : function() {
	var http = false;
	//Use IE's ActiveX items to load the file.
	if(typeof ActiveXObject != 'undefined') {
		try {http = new ActiveXObject("Msxml2.XMLHTTP");}
		catch (e) {
			try {http = new ActiveXObject("Microsoft.XMLHTTP");}
			catch (E) {http = false;}
		}
	//If ActiveX is not available, use the XMLHttpRequest of Firefox/Mozilla etc. to load the document.
	} else if (XMLHttpRequest) {
		try {http = new XMLHttpRequest();}
		catch (e) {http = false;}
	}
	return http;
},
// This function is called from the user's script. 
//Arguments - 
//	url	- The url of the serverside script that is to be called. Append all the arguments to 
//			this url - eg. 'get_data.php?id=5&car=benz'
//	callback - Function that must be called once the data is ready.
//	format - The return type for this function. Could be 'xml','json' or 'text'. If it is json, 
//			the string will be 'eval'ed before returning it. Default:'text'
load : function (url,params,method,callback) {
	this.init(); //The XMLHttpRequest object is recreated at every call - to defeat Cache problem in IE

	if(!this.http||!url) return;
	if (this.http.overrideMimeType) this.http.overrideMimeType('text/xml');
	this.callback=callback;
	var ths = this;//Closure
	if(method=="GET"){
		url += "\?" + params;
	}



	if (this.http.overrideMimeType) this.http.overrideMimeType('text/xml');

	//Kill the Cache problem in IE.
	var now = "uid=" + new Date().getTime();
	url += (url.indexOf("?")+1) ? "&" : "?";
	url += now;

	this.http.open(method, url, true);

	this.http.onreadystatechange = function () {//Call a function when the state changes.
		if(!ths) return;
		var http = ths.http;
		if (http.readyState == 4) {//Ready State will be 4 when the document is loaded.
			if(http.status == 200) {
				var result = "";
				if(http.responseText) result = http.responseText;

				//Give the data to the callback function.
				if(ths.callback) ths.callback(result);
			} else { //An error occured
				if(ths.error) ths.error()
			}
		}
	}
	if(method=="GET"){
		this.http.send(null);
	} else {
		this.http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		this.http.setRequestHeader("Content-length", params.length);
		this.http.setRequestHeader("Connection", "close");

		this.http.send(params);
	}
},
init : function() {this.http = this.getHTTPObject();}
}

 

 

Alt_F4, Thanks a lot for your help

I didn't use ajax before, therefor, I tried to match it with the database I posted before many time and I failed each time

Would you please fit the code to my database posted previously, I really need it and failed each time I tried :(

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.