I have 2 dropdown menus that read their data from a MySQL database. I use php for connecting to database. The second dropdowns should get populated based on the selection on the first dropdown. The process seems as below to me (correct me if I'm wrong):
- php section connects to MySQL database and populates dropdown1.
- user selects a value on dropdown1 and onchange event is called.
- within the onchange function (which is javascript), a query is sent to MySQL database to fetch values of dropdown2 based on the dropdown1 selection(here is php again, right?).
- dropdown2 gets populated.
I don't know how to use javascript and php together in order to do this task (number 3 above). or maybe this is not the way to do it at all. Please advise!
Here is my code. As you see below, I'm putting a javascript function within a php code which I suppose is wrong. That's where I got stuck!
<php
$sql="SELECT distinct category FROM table1";
$result=mysql_query($sql);
$optionsCat="";
while($row = mysql_fetch_row($result)){
$optionsCat.="<option value=\"$row[0]\">$row[0]</option>";
}
function genSubCat($catID){
$sql="SELECT distinct subcategory FROM table1 where category=".$catID;
$result=mysql_query($sql);
$optionsSubCat="";
while($row = mysql_fetch_row($result)){
$optionsSubCat.="<option value=\"$row[0]\">$row[0]</option>";
}
}
?>
<select name="catDropDown" onChange="genSubCat(this)">
<option value="0">Select category</option>
<?php echo $optionsCat?>
</select>
<select name="subcategoryDropDown">
<option value="0">Select subcategory</option>
<?php echo $optionsSubCat?>
</select>