PDA

View Full Version : need help with ajax and listboxes



cherubrock74
05-08-2009, 10:26 PM
I have two listboxes populated using data from a mysql database and ajax

my database has 3 fields: category, subcategory and subcategory2

I manage to have 2 listboxes to work and display "category" and "subcategory" but I would need a third listbox to display "subcategory2"
So far haven't received any reply...is it really hard to accomplish?

here is what I have so far:

code for the listboxes:


<html>
<body>

<script type="text/javascript">
function AjaxFunction(cat_id)
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck()
{
if(httpxml.readyState==4)
{

var myarray=eval(httpxml.responseText);
// Before adding new we must remove previously loaded elements
for(j=document.testform.subcat.options.length-1;j>=0;j--)
{
document.testform.subcat.remove(j);
}


for (i=0;i<myarray.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myarray[i];
optn.value = myarray[i];
document.testform.subcat.options.add(optn);

}
}
}
var url="dd.php";
url=url+"?cat_id="+cat_id;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateck;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
<form name="testform" method='POST' action='mainck.php'>
Select first one <select name=cat onchange="AjaxFunction(this.value);">
<option value=''>Select One</option>
<?
require "config.php";// connection to database
$q=mysql_query("select * from category ");
while($n=mysql_fetch_array($q)){
echo "<option value=$n[cat_id]>$n[category]</option>";
}

?>
</select>

<select name=subcat>

</select><br>
<br>
<input type=submit value=submit>
</form>
</body>
</html>


PHP code:


<?
$cat_id=$_GET['cat_id'];
require "config.php";
$q=mysql_query("select * from subcategory where cat_id='$cat_id'");
echo mysql_error();
$myarray=array();
$str="";
while($nt=mysql_fetch_array($q)){
$str=$str . "\"$nt[subcategory]\"".",";
}
$str=substr($str,0,(strLen($str)-1)); // Removing the last char , from the string
echo "new Array($str)";

?>