I'm new to jQuery and have a problem where I am unable to post a value which originated from a dependent dynamic dropdown list.
Here is the code I have written:
index.php
<form name="form1" action="test.php" method="post">
<table>
<tr>
<td>
<select id="branddd" onchange="change_brand()" required>
<option disabled="disabled" selected="selected" style="color:gray" required >brand</option>
<?php
$res=mysqli_query($link,"select * from brand");
while($row=mysqli_fetch_array($res))
{
?>
<option name="brand" value="<?php echo $row["id"];?>"><?php echo $row["name"];?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>
<div id="model">
<select name="model">
<option required>model</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit" value="submit"></td>
</tr>
</table>
Here is the JavaScript I have written to load data from MySQL into the 2nd dropdown box:
<script type="text/javascript">
function change_brand()
{
var xmlhttp=new XMLHttpRequest () ;
xmlhttp.open("GET","ajax.php? brand="+document.getElementById("branddd").value,false) ;
xmlhttp.send(null) ;
document.getElementById("model").innerHTML=xmlhttp.responseText ;
}
</script>
ajax.php:
<?php
$link=mysqli_connect("localhost","root","");
mysqli_select_db($link,"test_db");
$brand=$_GET["brand"];
if($brand!="")
{
$res=mysqli_query($link,"select * from model where brand_id=$brand");
echo "<select>";
while($row=mysqli_fetch_array($res))
{
echo "<option>"; echo $row["name"]; echo "</option>";
}
echo "</select>";
}
?>
Add name attribute in your select[id="branddd"] and add name="brand" to select tag not in options like,
<select id="branddd" name="brand" ...
Check you div is closed after your select[name="model"].And add required to the select box instead of its option
And at server end you need not to echo <select> again try this only,
while($row=mysqli_fetch_array($res))
{
echo "<option>".$row["name"]."</option>";
}
And add id to select instead of div
And if you are using jquery then your onchange event can be short like,
$(function(){
$('#branddd').on('change',function(){
this.value && // if value!="" then call ajax
$.get('ajax.php',{brand:this.value},function(response){
$('select[name="model"]').html(response);
});
});
});
In case of using jquery you must need to remove onchange from <select id="branddd" onchange="change_brand()" required> and would be just like <select id="branddd" required>