Bind DropDown Using jQuery AJAX, MYSQL and PHP

In this, we will bind a DropDown Category on the page and based on that dropdown we will bind another dropdown blogs using HTML, jQuery ajax, MYSQL and PHP.

For doing this you should have knowledge about

  • HTML
  • JQUERY
  • PHP
  • MYSQL
Let`s start

Create a PHP page and write the below code --

 <!DOCTYPE html>
 <?php $con=mysqli_connect("localhost","root","",'test'); ?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function()
{ $("#category").change(function(){ var value=$(this).val();
$.ajax({
type: "POST",
url: "GetList.php",
data: {ID:value}, // sending ID .
success: function(data)
{
// show response from the php script.
data=JSON.parse(data);
var blogs_list=" <option value=''>Select blogs </option>";
for (var i = 0; i < data.length; i++) {
blogs_list+=" <option value='"+ data[i].ID+"'>"+ data[i].Name+" </option>"; } $("#blogs").html(blogs_list);
}
}); });
});
</script>
</head>
<body>
<label>Category </label>
<select id="category">
<option value="">Select Category </option>
<?php $result=mysqli_query($con,"SELECT `ID`, `Category` FROM `tblcategorytest`");
if(mysqli_num_rows($result)>0)
{
while ($row=mysqli_fetch_array($result)) {
?>
<option value=" <?php echo $row['ID'] ?>"> <?php echo $row['Category'] ?> </option>
<?php
} }
?>
</select>
<br/> <br/>
<label>Blogs </label>
<select id="blogs">
<option value="">Select blogs </option>
</select>
</body>
</html>

Create another page that will give the list of the blogs on the ajax request in this example we are using GetList.php page.

 <?php
$id=$_REQUEST['ID'];
$con=mysqli_connect("localhost","root","",'test');
$myArray=array();
$result=mysqli_query($con,"SELECT `ID`, `Category`, `Name` FROM `tblblogstest` WHERE `Category`='$id'");
while ($row=mysqli_fetch_assoc($result))
{
$myArray[] = $row;
}
echo json_encode($myArray);
?>
OutPut: