By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,679 Members | 2,602 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,679 IT Pros & Developers. It's quick & easy.

Populating drop down menu from databse on onChnage() of first dropdown without refre

P: 45
Hi everyone,
I am new in php and ajax, i am facing the prob while i click on element of first drop down then in second dropdown all element showl come from database.
I mean i have three dropdown 1. category which comes from database 2. brand which comes from databse according to content of first dropdown . and 3. price which is static.
when i am doing these things without ajax on every onChange() thw whole page is refreshing that i do not want. and with ajax i am facing some prob like i have two php pages in one page all drop down is written and in socond php page only brand' s drop down is written i mean when i ma calling any category from databse then in brand dropdown category comes from database but suppose i am choosing a COPUTER then computer related brand comes from databse and replace the existing drop down . i do not want to replace the drop down i want to clear the content of first page dropdown and populate the content which comes from second page.

here is code:
selectbrand.js
Expand|Select|Wrap|Line Numbers
  1. var xmlHttp
  2.  
  3. function showBrand(str)
  4. xmlHttp=GetXmlHttpObject()
  5. if (xmlHttp==null)
  6.  {
  7.  alert ("Browser does not support HTTP Request")
  8.  return
  9.  }
  10. var url="search2.php"
  11. url=url+"?id="+str
  12. url=url+"&sid="+Math.random()
  13. xmlHttp.onreadystatechange=stateChanged 
  14. xmlHttp.open("GET",url,true)
  15. xmlHttp.send(null)
  16. }
  17. function stateChanged() 
  18. if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
  19.  { 
  20.  document.getElementById("txtHint").innerHTML=xmlHttp.responseText 
  21.  } 
  22. }
  23.  
  24. function GetXmlHttpObject()
  25. {
  26. var xmlHttp=null;
  27. try
  28.  {
  29.  // Firefox, Opera 8.0+, Safari
  30.  xmlHttp=new XMLHttpRequest();
  31.  }
  32. catch (e)
  33.  {
  34.  //Internet Explorer
  35.  try
  36.   {
  37.   xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  38.   }
  39.  catch (e)
  40.   {
  41.   xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  42.   }
  43.  }
  44. return xmlHttp;
  45. return true;
  46. }
  47.  
and first php page
search1.php

[PHP]<html>
<head>
<script src="selectbrand.js"></script>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>MB Solution Wikki</title>
<link rel="stylesheet" href="css_search.css" title="wikki">
</head>
<body>
<table cellpadding="0" cellspacing="0" width="100%">
<tbody><tr><td align="center">
<table style="margin-top: 1em; width: 80%;" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td align="left">
<div class="outer-box">
<div class="qbuilder-env" style=""></div>
<form method="get" name="f">
<div style="width: 100%;">
<h3>Find Article that have...</h3>
<input name="hl" value="en" type="hidden"><table cellpadding="2" cellspacing="0" width="100%">
<tbody>
<tr>
<td class="label">Keyword</td>
<td class="input"><input type="text" name="key" id="key" size="55"><td>
<td class="tip">&nbsp;</td>
</tr>
<tr>
<td class="label"><label>Category:</label></td>
<td class="input">
<select name="cat" id="cat" onChange="showBrand(this.value)">
<option value="0" >Select</option>
<?

$conn = mysql_connect("localhost", "root", "");
$db = mysql_select_db("gadget");

$result = mysql_query("select id, name from `category` GROUP BY name");
$i = 0;
while($rows = mysql_fetch_array($result))
{
$val[$i] = $rows['id'];
if($id == $val[$i]) $selected = "selected = 'selected'"; else $selected = "";
print "<option value='".$val[$i]."' ".$selected.">".$rows['name']."</option>";
$i++;
}

?>
</select> </td>
<input name="h2" type="hidden" value="" id="h2">
<td class="tip">&nbsp;</td></tr>
<tr>
<td class="label">

<label>Brand Name:</label></td>
<td class="input">
<div id="txtHint"> <select name="bname" size="1" id="bname">
<option value="0">Select</option>
<?

if($id == 0)
{
$results = mysql_query("select prod_name from `products` GROUP BY prod_name");
while($row = mysql_fetch_array($results))
{
//echo $row['prod_name'];
print "<option value='".$row['prod_name']."'>".$row['prod_name']."</option>";
}
}
else
{
$results = mysql_query("select prod_name from products where cat_id = '".$id."'");
while($row = mysql_fetch_array($results))
{
print "<option value='".$row['prod_name']."'>".$row['prod_name']."</option>";
}
}
?>
</select> </div> </td>
<td class="tip">&nbsp;</td></tr>
<tr>
<td class="label"><label>Price Range :</label></td>
<td id="or-cell" class="input">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td width="33%"> <select name="range">
<option value="0" selected>Select</option>
<option value="1000 - 2000">1000-2000</option>
<option value="2000 - 4000">2000-4000</option>
<option value="4000 - 10000">4000-10000</option>
<option value="10000 - 15000">10000-15000</option>
<option value="15000 - eof">15000 and above</option>
</select> </td>
</tr></tbody></table>

<input name="as_oq" value="" type="hidden"> </td>
<td class="tip">&nbsp;</td></tr></tbody></table>
<h3 align="right" style="margin-top: 1em;">
<label>
<?
$range = $_REQUEST['range'];
$range = trim($range);
$range1 = explode(" ",$range);
?>
<input type="submit" name="search" value="Search" id="search">
</label>
</h3></div>
<?php

if(isset($_REQUEST['search']))
{
if($_REQUEST['cat'] == 0 && $range1[2] != "eof")
{
$qry = "SELECT prod_descr, prod_img, name, prod_name, prod_price_gross from (SELECT * FROM `category` JOIN `products` ON category.id = products.cat_id) as cp WHERE cp.prod_name = '".$_REQUEST['bname']."' AND cp.prod_price_gross BETWEEN ".$range1[0]." and ".$range1[2]."";
}
elseif($_REQUEST['cat'] == 0 && $range1[2] == "eof")
{
$qry = "SELECT prod_descr, prod_img, name, prod_name, prod_price_gross from (SELECT * FROM `category` JOIN `products` ON category.id = products.cat_id) as cp WHERE cp.prod_name = '".$_REQUEST['bname']."' AND cp.prod_price_gross >= ".$range1[0];

}
elseif($range1[2] != "eof")
{
$qry = "SELECT prod_descr, prod_img, name, prod_name, prod_price_gross from (SELECT * FROM `category` JOIN `products` ON category.id = products.cat_id) as cp WHERE cp.id = '".$_REQUEST['cat']."' AND cp.prod_name = '".$_REQUEST['sel']."' AND cp.prod_price_gross BETWEEN ".$range1[0]." and ".$range1[2]."";
}
else
{
$qry = "SELECT prod_descr, prod_img, name, prod_name, prod_price_gross from (SELECT * FROM `category` JOIN `products` ON category.id = products.cat_id) as cp WHERE cp.id = '".$_REQUEST['cat']."' AND cp.prod_name = '".$_REQUEST['sel']."' AND cp.prod_price_gross >= ".$range1[0];
}
$search = mysql_query($qry) or die($qry);
while($show = mysql_fetch_array($search))
{
echo "<table width='100' border='0'>";
echo "<tr>";
echo '<td height="58"><table width="100" height="100" border="0">';
echo "<tr>";
echo '<td height="79">';
print "<img src=' ".$show['prod_img']." ' align='center' width='100' hieght='100' border='0'>";
echo "</td>";
echo "</tr>";
echo "</table>";
echo "</td>";
echo '<td valign="top">';
echo '<table width="200" border="0">';
echo "<tr>";
echo "<td><b>Category:</b>&nbsp;&nbsp;&nbsp;";
print $show['name'];
echo '</td>';
echo '</tr>';
echo '<tr>';
echo '<td height="31"><b>Product Name:</b>&nbsp;&nbsp;&nbsp;';
print $show['prod_name'];
echo "</td>";
echo "</tr>";
echo '<tr>';
echo '<td height="31"><b>Price:</b>&nbsp;&nbsp;&nbsp;';
print $show['prod_price_gross'];
echo "</td>";
echo "</tr>";
echo '<tr>';
echo '<td height="31"><b>Description:</b>&nbsp;&nbsp;&nbsp;';
print $show['prod_descr'];
echo "</td>";
echo "</tr>";
echo "</table>";
echo "</td>";
echo "</tr>";
echo "</table>";
}

}
?>
</div>

</form>

</div></td>
</tr></tbody></table></td></tr></tbody>
</table> </body></html>
[/PHP]
and scond php page is ;;

search2.php

[PHP] <?php

$id=$_REQUEST["id"];
//echo $id;
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("gadget", $con);

//echo "Select Brand:";
echo '<select name="sel" id="sel" size="1">';
echo '<option value="0">Select</option>';
//$row = mysql_fetch_array($result);
if($id == "0")
{
$results = mysql_query("select prod_name from `products` GROUP BY prod_name");
while($row = mysql_fetch_array($results))
{
//echo $row['prod_name'];
echo "<option value='".$row['prod_name']."'>".$row['prod_name']."</option>";
}
}
else
{
$results = mysql_query("select prod_name from `products` where cat_id = '".$id."'");
while($row = mysql_fetch_array($results))
{
echo "<option value='".$row['prod_name']."'>".$row['prod_name']."</option>";
}
}

echo "</select";
mysql_close($con);
?>[/PHP]
Sep 12 '08 #1
Share this Question
Share on Google+
11 Replies


acoder
Expert Mod 15k+
P: 16,027
Instead of returning the HTML code to replace the drop down, return a string delimited by a special character which you can use to populate the drop down element. Alternatively, you can use JSON or XML.

PS. please use code tags when posting code. See How to ask a question.
Sep 12 '08 #2

P: 45
Instead of returning the HTML code to replace the drop down, return a string delimited by a special character which you can use to populate the drop down element. Alternatively, you can use JSON or XML.

PS. please use code tags when posting code. See How to ask a question.
Hi,
thanx for reply .now i am using ur solution but in javascript populate function is not working . on click of first dropdown list it remove all yhe element of second dropdown but in case of filling second dropdown its not working..
javascript code
Expand|Select|Wrap|Line Numbers
  1. // for removing element
  2.  
  3. function dropdown(str,text,value)
  4. {
  5. var item=str.split(',');
  6. var obj=document.getElementById("bname");
  7. //var opt = document.createElement("bname");
  8.  
  9. len=parseInt(obj.length);
  10. for ( i=0;i<len;i++)
  11.     {
  12.         obj.options[i]=null;
  13.  
  14.     }
  15. //for adding element
  16.  
  17.     for(i=0;i<item.length;i++)
  18.     {
  19.         obj.options[obj.options.length].value=item[i];
  20.         obj.options[obj.options.length].text=item[i];
  21.         //alert(obj.options[i].text);
  22. //var optn = document.createElement("bname");  
  23. //optn.text = text;  
  24. //optn.value = value;
  25. //str.options.add(optn);
  26. */                
  27.     }
please do something ...
Sep 13 '08 #3

acoder
Expert Mod 15k+
P: 16,027
Show the code/line where you call dropdown().
Sep 13 '08 #4

P: 45
Show the code/line where you call dropdown().
here is the code where dropdown is calling

Expand|Select|Wrap|Line Numbers
  1. function stateChanged() 
  2. if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
  3.  { 
  4.  //document.getElementById("txtHint").innerHTML=xmlHttp.responseText 
  5. dropdown(xmlHttp.responseText);
  6.  } 
  7. }
  8.  
line 6
Sep 13 '08 #5

acoder
Expert Mod 15k+
P: 16,027
What's the response from the PHP script?
Sep 13 '08 #6

P: 45
What's the response from the PHP script?
it removes all the element from second dropdown on click of the category of first dropdoen but not populating ...
Sep 14 '08 #7

acoder
Expert Mod 15k+
P: 16,027
No, I meant if you run the PHP script directly without Ajax. Do you get the expected response?
Sep 14 '08 #8

P: 45
No, I meant if you run the PHP script directly without Ajax. Do you get the expected response?
yes i am getting expected response but there is a prob it refresh page on every change of category that i do not want...
Sep 16 '08 #9

acoder
Expert Mod 15k+
P: 16,027
I meant the responseText value. You could alert to check.

Try replacing the lines:
Expand|Select|Wrap|Line Numbers
  1. obj.options[obj.options.length].value=item[i];
  2. obj.options[obj.options.length].text=item[i];
with
Expand|Select|Wrap|Line Numbers
  1. obj.options[obj.options.length] = new Option(item[i], item[i]);
Sep 16 '08 #10

P: 45
I meant the responseText value. You could alert to check.

Try replacing the lines:
Expand|Select|Wrap|Line Numbers
  1. obj.options[obj.options.length].value=item[i];
  2. obj.options[obj.options.length].text=item[i];
with
Expand|Select|Wrap|Line Numbers
  1. obj.options[obj.options.length] = new Option(item[i], item[i]);
thanx dude...
its working now...i was making a mistake in php page i used implode function thats why not working and now i using string concate operation by using this code is working properly
but anyway thanx for your co-operation...
Sep 19 '08 #11

acoder
Expert Mod 15k+
P: 16,027
...which is why I was saying that you should check the PHP page.

Anyway, glad it's working.
Sep 19 '08 #12

Post your reply

Sign in to post your reply or Sign up for a free account.