Download
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Loading of ComboBox using jQuery and Ajax PHP and Mysqli</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#loader').hide();
$('#show_heading').hide();
$('#search_category_id').change(function(){
$('#show_sub_categories').fadeOut();
$('#loader').show();
$.post("get_child_categories.php", {
parent_id: $('#search_category_id').val(),
}, function(response){
setTimeout("finishAjax('show_sub_categories', '"+escape(response)+"')", 400);
});
return false;
});
});
function finishAjax(id, response){
$('#loader').hide();
$('#show_heading').show();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
</script>
<style>
.both h4{ font-family:Arial, Helvetica, sans-serif; margin:0px; font-size:14px;}
#search_category_id{ padding:3px; width:200px;}
#sub_category_id{ padding:3px; width:200px;}
.both{ float:left; margin:0 15px 0 0; padding:0px;}
</style>
</head>
<body>
<?php include('dbcon.php');?>
<div style="padding-left:30px;">
<form action="#" name="form" id="form" method="post" onsubmit="return alert_id();" enctype="multipart/form-data">
<div class="both">
<h4>Select Category</h4>
<select name="search_category" id="search_category_id">
<option value="" selected="selected"></option>
<?php
$sql="SELECT * from ajax_category";
if ($result=mysqli_query($conn,$sql))
{
while ($row=mysqli_fetch_row($result)) {
$id = $row[0];
$category = $row[2];
echo "<option value='$id'>$category</option>";
}
mysqli_free_result($result);
}
mysqli_close($conn);
?>
</select>
</div>
<div class="both">
<h4 id="show_heading">Select Sub Category</h4>
<div id="show_sub_categories" align="center">
<img src="img/loader.gif" style="margin-top:8px; float:left" id="loader" alt="" />
</div>
</div>
</form>
</div>
</body>
</html>
//get_child_categories.php
<?php
include('dbcon.php');
if($_REQUEST)
{
$id = $_REQUEST['parent_id'];
$query="SELECT * from ajax_categories2 where pid = ".$id;
if ($result=mysqli_query($conn,$query)){
?>
<select name="sub_category" id="sub_category_id">
<option value="" selected="selected"></option>
<?php
while ($row=mysqli_fetch_row($result)) { ?>
<option value="<?php echo $row[2];?> ID=<?php echo $row[0];?>"><?php echo $row[2];?></option>
<?php } ?>
</select>
<?php }
}
?>
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>
