Dynamic Dependent Select Box using jQuery, Ajax and PHP


The dynamic dependent select box is used to auto-populate the dependent data in the dropdown list. Bases on the drop-down selection, the dependent data are retrieved from the database and display in the next select box. Generally, the dynamic dependent select box is used to implement country state city dropdown functionality. Using Ajax and PHP, you can easily implement dynamic dependent dropdown without page refresh.

In this tutorial, we will show you how to implement relational dropdown of country state city using jQuery, Ajax, PHP, and MySQL. Means state is related to country and city is related to the state. Based on changing of country & state, respective state & city will be fetched from the database without reloading the page using jQuery, Ajax, PHP, and MySQL.

The example code initially shows all countries in the country dropdown. When a country is chosen, the respective states will be fetched from the MySQL database and appear in the state dropdown. Alike when a state is chosen, the respective cities will be fetched from the MySQL database and appear in the city dropdown.

Create Database Tables

To store the data of country, state, and city, three tables need to be created in the database. Also, there would be a relationship between countries, states, and cities table. The states table has a relation with countries table and cities table has a relation with states table.

countries Table:
The following SQL creates a countries table in the MySQL database.

CREATE TABLE `countries` (
 `country_id` int(11) NOT NULL AUTO_INCREMENT,
 `country_name` varchar(50) CHARACTER SET utf8 NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0:Blocked, 1:Active',
 PRIMARY KEY (`country_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

states Table:
The following SQL creates a states table in the MySQL database.

CREATE TABLE `states` (
 `state_id` int(11) NOT NULL AUTO_INCREMENT,
 `state_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `country_id` int(11) NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0:Blocked, 1:Active',
 PRIMARY KEY (`state_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

cities Table:
The following SQL creates a cities table in the MySQL database.

CREATE TABLE `cities` (
 `city_id` int(11) NOT NULL AUTO_INCREMENT,
 `city_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `state_id` int(11) NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0:Blocked, 1:Active',
 PRIMARY KEY (`city_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php)

The dbConfig.php file is used to connect and select the database. Specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName).

<?php
//Database credentials
$dbHost     'localhost';
$dbUsername 'root';
$dbPassword 'root';
$dbName     'codexworld';

//Connect and select the database
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName);

if (
$db->connect_error) {
    die(
"Connection failed: " $db->connect_error);
}
?>

Dynamic Dependent Select Boxes (index.php)

HTML & PHP Code:
Initially, the country data will be retrieved from the MySQL database and listed in the country dropdown. Once a value is selected in the country dropdown, the respective data will be listed in the state and city dropdown.

<?php
//Include the database configuration file
include 'dbConfig.php';

//Fetch all the country data
$query $db->query("SELECT * FROM countries WHERE status = 1 ORDER BY country_name ASC");

//Count total number of rows
$rowCount $query->num_rows;
?> <select 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> <select id="state"> <option value="">Select country first</option> </select> <select id="city"> <option value="">Select state first</option> </select>

JavaScript Code:
Once a country is selected, the dependent states are retrieved via ajaxData.php file using jQuery and Ajax. Likewise, on selecting the state, the dependent cities are retrieved via ajaxData.php file using jQuery and Ajax.

At first, include the jQuery library.

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

The following JavaScript code sends the request to the ajaxData.php file using ajax to get the state and city data from the database. Based on the Ajax response, it displays the returned drop-down HTML to the dependent select box.

<script type="text/javascript">
$(document).ready(function(){
    $('#country').on('change',function(){
        var countryID = $(this).val();
        if(countryID){
            $.ajax({
                type:'POST',
                url:'ajaxData.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:'ajaxData.php',
                data:'state_id='+stateID,
                success:function(html){
                    $('#city').html(html);
                }
            }); 
        }else{
            $('#city').html('<option value="">Select state first</option>'); 
        }
    });
});
</script>

Retrieved Dependent Data (ajaxData.php)

The ajaxData.php is called by the Ajax to retrieve the dependent data from the database using PHP and MySQL. The state and city dropdown HTML are returned to the success method of the Ajax request.

  • If country_id is provided, the respective states are fetched from the database and a state dropdown list is rendered.
  • If state_id is provided, the respective cities are fetched from the database and a city dropdown list is rendered.
<?php
//Include the database configuration file
include 'dbConfig.php';

if(!empty(
$_POST["country_id"])){
    
//Fetch all state data
    
$query $db->query("SELECT * FROM states WHERE country_id = ".$_POST['country_id']." AND status = 1 ORDER BY state_name ASC");
    
    
//Count total number of rows
    
$rowCount $query->num_rows;
    
    
//State option list
    
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>';
    }
}elseif(!empty(
$_POST["state_id"])){
    
//Fetch all city data
    
$query $db->query("SELECT * FROM cities WHERE state_id = ".$_POST['state_id']." AND status = 1 ORDER BY city_name ASC");
    
    
//Count total number of rows
    
$rowCount $query->num_rows;
    
    
//City option list
    
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>';
    }
}
?>

Conclusion

This tutorial shows how you can implement Ajax country state city dropdown in PHP. But you can easily extend the dynamic dependent select boxes functionality as per the requirement. For fast response, use the JSON data type in Ajax and PHP.

How to Get JSON Data from PHP Script using jQuery Ajax

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Recommended Tutorials For You

43 Comments

  1. Ben Said...
  2. Justin Said...
    • CodexWorld Said...
  3. Rasika Said...
  4. Diego Said...
  5. Jestoni Said...
  6. Nitish Saini Said...
  7. Chintha Said...
  8. Mpho Said...
  9. Rahamath Said...
  10. Sujit Maharjan Said...
  11. Umair Said...
  12. Hossein Said...
  13. Deepak Said...
  14. Smith Said...
    • CodexWorld Said...
  15. Pritam Saha Said...
  16. Raditya Said...
  17. Jorz Said...
  18. Nabeel Farrukh Said...
  19. Manuel FΓ©lix Said...
  20. Walidoux Said...
  21. Friency Fernandez Said...
  22. Manoj P Said...
    • CodexWorld Said...
  23. Mahesh Said...
  24. Mahesh Said...
  25. Sasikumar Said...
  26. Ivan Said...
  27. Ivan Said...
  28. Satyasundar Das Said...
  29. Bishop Said...
  30. Sergiu Said...
    • CodexWorld Said...
  31. Peterpeterson Said...
  32. SteveRogers Said...
  33. Anupam Said...
  34. Manoj Goyal Said...
  35. Fahad Shah Said...
  36. Viorica Said...
  37. Pradeep Kumar Said...
  38. Mahmud Said...

Leave a reply