Dynamic dependent country, state and city Select Box using Jquery and Ajax in Php.

I have received many users requests for making the dynamic dependent Country, State and City select box using jQuery and ajax in PHP. After getting lot of requests, I am going to explain how to create auto select country, state and city dropdown using help of jQuery, Ajax and Php.

This tutorial is very useful to include this feature in user registration form or address form. In this tutorial, I have include dynamic feature. When you select country from select box then next select box automatically generate state related to that country. When you select state then it automatically generate city in next select box.

Output:

Dynamic dependent select box jquery php

Implementation of Database and Tables:

First you need to create a Database name location. After creating database (location), you will have to create three Table countries, states and cities.
Here Table countries has relation with Table states through country_id and states has relation with Table cities through state_id.

countries (table):

This table contains two columns (country_id, country_name). To create this table you will have to execute code that is given below:

CREATE TABLE `countries` (
  `country_id` int(12) NOT NULL,
  `country_name` varchar(40) CHARACTER SET utf8 NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

states (table):

This table contains three columns (state_id, state_name, country_id). To create this table you will have to execute code that is given below:

CREATE TABLE `states` (
  `state_id` int(11) NOT NULL,
  `state_name` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `country_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

cities (table):

This table contains three columns (city_id, city_name, state_id). To create this table you will have to execute code that is given below:

CREATE TABLE `cities` (
  `city_id` int(11) NOT NULL,
  `city_name` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `state_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

config.php:

This PHP file is used to connect and use the database (location).

<?php
$con=mysqli_connect('localhost','root','','location');
if ($con->connect_error) {
die("Database Connection failed: " . $con->connect_error);
}
?>

index.html:

In this file I have used JavaScript, Jquery Library and some Php code. I have used JavaScript code to getting data of state and city from ajaxFile.php using help of Ajax. It also displays the returned HTML of ajaxFile.php file to the respective selct box.

<html>
<head>
<style type="text/css">
select {   
 width: 300px; 
}
</style>
<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:'ajaxFile.php',
                data:'country_id='+countryID,
                success:function(html){
                    $('#state').html(html);
                    $('#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:'ajaxFile.php',
                data:'state_id='+stateID,
                success:function(html){
                    $('#city').html(html);
                }
            }); 
        }else{
            $('#city').html('<option value="">Select state first</option>'); 
        }
    });
});
</script>
</head>
<body>
<center>

                
    <div style='margin-top:50px;'>
	<img src="https://www.coderglass.com/images/logo.png"><br>
	<h4>Varun Singh's Tech Blog</h4>
	<h2>Country, State and City dropdown box using jquery in Php.</h2>
	<br>
	
    <?php
    //Include database configuration file
    include('config.php');
    
    //Get all country data
    $query = "SELECT * FROM countries  ORDER BY country_name ASC";
    $run_query = mysqli_query($con, $query);
    //Count total number of rows
	$count = mysqli_num_rows($run_query);
    
    ?>
    <select name="country" id="country">
        <option value="">Select Country</option>
        <?php
        if($count > 0){
            while($row = mysqli_fetch_array($run_query)){
				$country_id=$row['country_id'];
				$country_name=$row['country_name'];
                echo "<option value='$country_id'>$country_name</option>";
            }
        }else{
            echo '<option value="">Country not available</option>';
        }
        ?>
    </select><br><br>
    
    <select name="state" id="state">
        <option value="">Select country first</option>
    </select>
	<br><br>
    
    <select name="city" id="city">
        <option value="">Select state first</option>
    </select>
    </div>
	</center>
</body>
</html>

ajaxFile.php:

This file is called by the Ajax and we get state name and city name from the database according to country_id and state_id. This file also returns select options HTML to the Ajax function.

<?php
//Include database configuration file
include('config.php');

if(isset($_POST["country_id"])){
    //Get all state data
	$country_id= $_POST['country_id'];
    $query = "SELECT * FROM states WHERE country_id = '$country_id' 
	ORDER BY state_name ASC";
	$run_query = mysqli_query($con, $query);
    
    //Count total number of rows
    $count = mysqli_num_rows($run_query);
    
    //Display states list
    if($count > 0){
        echo '<option value="">Select state</option>';
        while($row = mysqli_fetch_array($run_query)){
		$state_id=$row['state_id'];
		$state_name=$row['state_name'];
        echo "<option value='$state_id'>$state_name</option>";
        }
    }else{
        echo '<option value="">State not available</option>';
    }
}

if(isset($_POST["state_id"])){
	$state_id= $_POST['state_id'];
    //Get all city data
    $query = "SELECT * FROM cities WHERE state_id = '$state_id' 
	ORDER BY city_name ASC";
    $run_query = mysqli_query($con, $query);
    //Count total number of rows
    $count = mysqli_num_rows($run_query);
    
    //Display cities list
    if($count > 0){
        echo '<option value="">Select city</option>';
        while($row = mysqli_fetch_array($run_query)){
		$city_id=$row['city_id'];
		$city_name=$row['city_name']; 
        echo "<option value='$city_id'>$city_name</option>";
        }
    }else{
        echo '<option value="">City not available</option>';
    }
}
?>