Dynamic Dependent Select Box Using Jquery Ajax PHP & Mysql

Hi Guys, We are once again here to help our fellow Developers with yet another interesting topic i.e. Dynamic Dependent Select Box powered by (jQuery, Ajax, PHP & MySQL).

In this tutorial, we’ll implement relational drop-down for dependent Country State City. We will make State options available to the user based on the Country he selects and similarly Cities based on the State he selects.

We will go through the whole scenario step by step:

Before we start we should know that we will need the database for Country, State and Cities. If you don’t have the database you can download it here Download Country, State and City database.

Create a database named phphurdles and import the above table into the database.

So let’s start the coding part.

Step-1: The primary step is to create a database connection.  Create a file database.php and connect your project with the related database i.e.  (phphurdles).

database.php

**********************************************************************************

<?php
$dbHost=’localhost’;
$dbUsername=’root’;                //(Insert your database user)
$dbPassword=’ ‘;                      //(Insert your database password)
$dbName=’phphurdles’;       // Change your database name accordingly

$db=new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);

if($db->connect_error){
die(“Either database or the credentials are wrong.:”.$db->connect_error);

}

?>

**********************************************************************************


 

Step-2:

Now, our second step would be to fetch all the data from countries table and populate in the drop down.

For example:

<?php
$query=$db->query(“Select * From countries Where ORDER BY name ASC”);
$rowcount=$query->num_rows;

?>
<!– Select Box for county where data is fetch through select query!–>
<label for=”country”>Country</label>
<select name=”country” id=”country” >
<option value=””>Select Country</option>
<?php
if($rowcount>0){

while($row=$query->fetch_assoc()){
echo ‘<option value=”‘.$row[‘id ‘].'”>’.$row[‘name’].'</option>’;
}

}
else{
echo ‘<option value=””>Country Not Available</option>’;

}
?>

</select>
?>

 

Step-3:

index.php

This file contains jQueryHTML and PHP code.

The following code is used for getting the state and city data from the dynamic ajax.php file using on change JavaScript function. Once, you select the country from the drop-down (Country) option; on change function will be called and get the desired output from ajax.php page and display on the particular location on the same page.

 

 

**********************************************************************************

<script src=”jquery.min.js”></script>
<script type=”text/javascript”>
$(document).ready(function()
{
$(‘#country’).on(‘change’,function()
{
var countryID =$(this).val();
if(countryID)

{
$.ajax
({
type:’POST’,
url:’ajax.php’,
data:’country_id=’+countryID,
success:function(data)
{

$(‘#state’).html(data);
$(‘#city’).html(‘<option value=””>Select State First</option>’);
}
});
}else
{
$(‘#state’).html(‘<option value=””>Select Country First</option>’);
$(‘#city’).html(‘<option value=””>Select State First</option>’);

}

})

$(‘#state’).on(‘change’,function()
{
var stateID =$(this).val();
if(stateID)

{
$.ajax
({
type:’POST’,
url:’ajax.php’,
data:’state_id=’+stateID,
success:function(data)
{

$(‘#city’).html(data);
}
});
}else
{
$(‘#city’).html(‘<option value=””>Select State First</option>’);
}

})

});
</script>

**********************************************************************************

Using HTML and PHP country select box is displayed along with state and city select box.

**********************************************************************************

<?php
$query=$db->query(“Select * From countries Where status=’1′ ORDER BY country_name ASC”);
$rowcount=$query->num_rows;

?>

<div>
<!– Select Box for county where data is fetch through select query!–>
<label for=”country”>Country</label>
<select name=”country” id=”country” >
<option value=””>Select Country</option>
<?php
if($rowcount>0){

while($row=$query->fetch_assoc()){
echo ‘<option value=”‘.$row[‘country_id’].'”>’.$row[‘country_name’].'</option>’;
}

}
else{
echo ‘<option value=””>Country Not Available</option>’;

}
?>

</select>
</div>
<!– Select Box for state –>
<div>
<label for=”state”>State</label>
<select name=”state” id=”state” >
<option value=””>Select State</option>
</select>
</div>
<!– Select Box for City–>
<div>
<label for=”city”>City</label>
<select name=”city” id=”city” >
<option value=””>Select City</option>
</select>
</div>

*********************************************************************************

Step-4:

Here is the Ajax file which is containing the dynamic value on the selection basis.

**********************************************************************************

<?php
require_once(‘database.php’);

//Ajax call for state where values are going to be fetch by countries table on the behalf of country_id.
if(isset($_POST[‘country_id’]) && !empty($_POST[‘country_id’])){

$query = $db->query(“SELECT * FROM states WHERE country_id = “.$_POST[‘country_id’].”  ORDER BY state_name ASC”);
$rowCount= $query->num_rows;

if($rowCount>0){
echo ‘<option value=””>Select State</option>’;
while($row=$query->fetch_assoc()){

echo ‘<option value=”‘.$row[‘state_id’].'”>’.$row[‘state_name’].'</option>’;
}

}
else{

echo ‘<option value””>State Not Available</option>’;

}
}

//Ajax call for fetch the cities related to the specific state.
if(isset($_POST[‘state_id’]) &&!empty($_POST[‘state_id’])){

$query=$db->query(“SELECT * FROM cities WHERE state_id=”.$_POST[‘state_id’].” ORDER BY city_name ASC”);
$rowCount=$query->num_rows;

if($rowCount>0){
echo ‘<option value=””>Select City</option>’;
while($row=$query->fetch_assoc()){

echo ‘<option value=”‘.$row[‘city_id’].'”>’.$row[‘city_name’].'</option>’;
}

}
else{

echo ‘<option value””>City Not Available</option>’;

}
}
?>

*************************************************************************************

Do not forget to include the database.php in ajax.php file. You can download the whole code with counter-state-city database file here PHP script for dependent drop-down (Country-State-City) using ajax and mysql

We Hope this article will help you to find the solution of your dependent drop-down select box.

So Keep Moving!  Hurdles Are Meant To Be Jumped Over.

 

7 Comments

  1. Nahid said:

    thanks!

    April 9, 2017
    Reply
  2. Remarkable issues here. I am very glad to see your article.
    Thanks so much and I am having a look ahead to contact you.
    Will you kindly drop me a e-mail?

    May 19, 2017
    Reply
    • Deepak Shah said:

      thankyou you so much you can comment us with any of your query without any hesitaion we are always ready to help you

      May 21, 2017
      Reply
  3. dave said:

    how do i convert to mysqli ?

    May 26, 2017
    Reply
    • Deepak Shah said:

      Sorry we didn’t get what you are saying ….if you are talking about the blog then the tutorial dependent select box is already in using mysqli anf if you are asking how you can use mysqli for database connection in your project then our team will soon come up with a tutorial on database connection using mysqli.
      please Elobrate?

      May 27, 2017
      Reply
  4. Manjusha Mishra said:

    Great tutorial. This is fully informative tutorial about dynamic select box using jQuery. It save lot of time. It just made my work easier. I’m saving for this future reference.

    Thanks,

    August 12, 2017
    Reply
  5. Ravina said:

    Thanks alot.

    November 2, 2017
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *