Dynamic Dependent Select Box using jQuery, Ajax and PHP

There are many situation where you will need to dynamic dropdown like you have a dropdown which contains countries name and you have to find all state of selected country in select box or dropdown. Here we are going to tell you how to make dynamic select box using jQuery, Ajax and PHP. Firstly we will fetch all country from country table then we will use Ajax and jQuery to fetch all state of selected country. After getting all state we will append to all state on state dropdown.

Here we are using MySQLi as a database which contains two table country and state. For making dynamic dependent select box use following steps as shown below:

1.  Create database Discussdesk from phpmydmin and can also use following sql query to create it as shown below:

CREATE DATABASE discussdesk

2. Create two table countries and states from phpmyadmin. You can also create by  following sql query as show below:

CREATE TABLE IF NOT EXISTS `countries` (
  `id` int(11) NOT NULL,
  `sortname` varchar(3) NOT NULL,
  `name` varchar(150) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=247 DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `states` (
  `id` int(11) NOT NULL,
  `name` varchar(30) NOT NULL,
  `country_id` int(11) NOT NULL DEFAULT '1'
) ENGINE=InnoDB AUTO_INCREMENT=4121 DEFAULT CHARSET=latin1;

 

These following above query will create two table. To insert data in these table you can get data by clicking download button or import all table with data. We are attaching discussdesk.sql file to import all table with data in discussdesk database.

3.  Create db_config.php file with following code as shown below and put your database name what you made from phpmyadmin.

<?php
$host= "localhost";
$username= "root";
$password = "";
$db_name = "Your_database";
$db = new mysqli($host,$username,$password,$db_name);
if($db->connect_error)
{
	die("connection failed:". $db->connect_error);
	
}
?>

4.  Create Second file country.php in which we fetch all countries from database and append in select box. Here we fire function on onchange event of country select box in which using Ajax it will go on state.php page with country id to fetch all record from states table and return in Ajax response. After getting response in success function we append response to state dropdown box basis of id. The code of country.php is as follows:

<style>
.dropdown
{	
width: 150px;
height: 30px;
font-size: 18px;
}
.space
{
margin-left: 40px;	
}
</style>
<?php
include('db_config.php');
$sql= "select * from countries";
$query = $db->query($sql);
$data = $query->fetch_assoc();

?>

<label>Country</label>
<select name="counntry" id="country" class="dropdown" onchange="change_country();">
<option value="">Select Country</option>
<?php while($row = $query->fetch_assoc()) { ?>
	<option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
<?php } ?>
</select>

<span class="space"></span>
<label>State</label>
<select name="state" id="state" class="dropdown">
<option value="">Select State</option>

</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<script>
functionchange_country()
{
	var country = $("#country").val();
	
	   $.ajax({
		type: "POST",
		url: "state.php",
		data: "country="+country,
		cache: false,
		success: function(response)
			{
					//alert(response);return false;
				$("#state").html(response);
			}
			});
	
}
</script>

5.  Create another file state.php file as shown below. This file fetch all record from states table basis of country_id column and return all record to Ajax success function.

<?php
include('db_config.php');
$country = $_POST['country'];
$sql= "select * from states where country_id='$country'";
$query = $db->query($sql);
echo '<option value="">Select State</option>';
while($res = $query->fetch_assoc()){
echo '<option value="'.$res['name'].'">'.$res['name'].'</option>';
	
}
?>

I hope this article will help to make two Dynamic Dependent Select Box. Still you have any query then feel free to comment below.

Share this Article on Social Media

All of my Scripts are ready to customized as per your requirement. Feel free to contact for script customization.

Contact me at discussdesk@gmail.com

"Note : It will be charged as per your customization requirement :)"

Get Updates, Scripts & Other Tutorials to Directly to your Email

Over 20000+ Happy Readers already subscribed. (We don't send spam email). Every email subscriber can get our latest updates and download our 100+ scripts.

Comments