Reputation: 1645
I have a problem in populating dropdown lists.
I have a dropdown from which the user selects the branch, and a second dropdown that shows related options.
HTML
<select id="first-choice" onchange="leaveChange()">
<option selected value="base">Please Select</option>
<option value="CSE">CSE</option>
<option value="ECE">ECE</option>
<option value="EEE">EEE</option>
<option value="MECH">MECH</option>
</select>
<br>
<select id="second-choice">
<option>Please choose from above</option>
</select>
JS
function leaveChange(){
//what to insert here;
}
PHP
$branch=$_GET['branch'];
$username = "jaggu";
$password = "8374";
$hostname = "localhost";
$dbhandle = mysqli_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
$selected = mysqli_select_db($dbhandle,"test") or die("Could not select examples");
$query = "SELECT * FROM `register` WHERE classid LIKE '%".$branch."%'";
$result = mysqli_query($dbhandle,$query);
$row = mysqli_fetch_object($result);
$query1="SELECT * FROM `examdup` WHERE `classid` LIKE '%".$branch."%'";
$result1= mysqli_query($dbhandle,$query1);
while ($row1= mysqli_fetch_object($result1)) {
echo '<option value="'.$row1->month_year.'">'. $row1->title.'</option>';
}
Upvotes: 2
Views: 2238
Reputation: 488
Here is the perfect answer to your question: W3Schools AJAX PHP Database
And if you integrate this example into your code, it should look like this:
HTML
<select id="first-choice" onchange="leaveChange(this.value)">
<option selected value="">Please Select</option>
<option value="CSE">CSE</option>
<option value="ECE">ECE</option>
<option value="EEE">EEE</option>
<option value="MECH">MECH</option>
</select>
<br>
<select id="second-choice">
<option>Please choose from above</option>
</select>
JS
function leaveChange(branch){
if (branch == "") {
document.getElementById("second-choice").innerHTML = "<option>Please choose from above</option>";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("second-choice").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","test.php?branch="+branch,true);
xmlhttp.send();
}
}
You should replace the name of file test.php
to yours at this line:
xmlhttp.open("GET","test.php?branch="+branch,true);
Upvotes: 1