PHPGurukul

jQuery Dependent DropDown List – States and Districts

In this tutorial, we are going to see how to change the district dropdown list option based on the selected state name.
For Localhost create a database with name demos and import the SQL file available inside the download package.

View Demo

In this example, we have two dropdown for listing states and districts. On changing states dorpdown values, the corresponding district dropdown values will be loaded dynamically using jQuery AJAX.
HTML Code for state and dsitrict dropdown

<form name="insert" action="" method="post">
<table width="100%" height="117"  border="0">
<tr>
<th width="27%" height="63" scope="row">Sate :</th>
<td width="73%"><select onChange="getdistrict(this.value);"  name="state" id="state" class="form-control" >
<option value="">Select</option>
<?php $query =mysqli_query($con,"SELECT * FROM state");
while($row=mysqli_fetch_array($query))
{ ?>
<option value="<?php echo $row['StCode'];?>"><?php echo $row['StateName'];?></option>
<?php
}
?>
</select></td>
</tr>
<tr>
<th scope="row">District :</th>
<td><select name="district" id="district-list" class="form-control">
<option value="">Select</option>
</select></td>
</tr>
</table>
</form>

Getting States using jQuery AJAX
This script contains function that will be called on changing state dropdown values. It will send AJAX request to a PHP page to get corresponding district dropdown options.

<script>
function getdistrict(val) {
$.ajax({
type: "POST",
url: "get_district.php",
data:'state_id='+val,
success: function(data){
$("#district-list").html(data);
}
});
}
</script>

 Read State Database using PHP
This PHP code connects database to retrieve district table values based on the country id passed by jQuery AJAX call.

<?php
require_once("config.php");
if(!empty($_POST["state_id"]))
{
$query =mysqli_query($con,"SELECT * FROM district WHERE StCode = '" . $_POST["state_id"] . "'");
?>
<option value="">Select District</option>
<?php
while($row=mysqli_fetch_array($query))
{
?>
<option value="<?php echo $row["DistrictName"]; ?>"><?php echo $row["DistrictName"]; ?></option>
<?php
}
}
?>

For Localhost create a database with name demos and import the sql file available inside download package.
View Demo

Download Source Code(JQuery Dependent DropDown List – States And Districts)
Size: 33.3 KB
Version: V 1.1

Anuj Kumar

This is Anuj Kumar. I’m a professional web developer with 4+ year experience. I write blogs in my free time. I love to learn new technologies and share with others.
I founded PHPGurukul in September 2015. The main aim of this website to provide PHP, Jquery, MySQL, PHP Oops and other web development tutorials.
.

Recommended Tutorials for you


6 comments

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.