Dynamic Dependent Select Box using jQuery and Ajax

Demo Download

We often see dynamic dependent select box in website, which are part of web form. Today i will share how to use dynamic dependent select box using jQuery and ajax. I will use an example of country and city, when you will select any country, its cities will be available in the below select box without refresh or reload the page this is the power of Ajax.

Steps to Create Dynamic Dependent Select Box using jQuery and Ajax

  1. Create a Database
  2. Create Two Tables of County and City and Insert Data in Both Table
  3. Create a Database Connection File
  4. Create Index File Which Using JQuery and Ajax
  5. Create PHP Action File

1. Create a Database

Create a database with name parent_child_select. For this purpose run the following query in MySQL.

2. Create Two Tables of County and City and Insert Data in Both Table

Create two tables with name county and city and insert sample data  in database by using the following queries. For your ease i have also attached the SQL file in download file just import this file in SQL and it will create tables with sample data.

3. Create a Database Connection File

Create a file with name db.php and copy paste the below code in that file. Make sure that you changed your database, username, password and host.

4. Create Index File Which Using JQuery and Ajax

Create a file with name index.php and copy paste the below code in this file. Note that I  have added the jQuery and Ajax script in the footer of this file.

5. Create PHP Action File

Create a file with name ajax.php and paste the below script there.

Demo Download

If you found this tutorial helpful so share it with your friends, developer groups and leave your comment.

Article By
Javed Ur Rehman is a passionate blogger and web developer, he loves to share web development tutorials and blogging tips. He usually writes about HTML, CSS, JavaScript, Jquery, Ajax, PHP and MySQL.

15 Comments

  1. Hi there,
    great tutorial! i’m having trouble implemented the last section. Once I choose an option from the first drop down box, the second drop down box goes completely blank, even removing the original default text. I have tried debugging this for many days and I have managed to find out that the problem lies in the AJAX file. For some reason it appears that I can’t connect to any sql server from the ajax file.
    -I can connect to the ajax file fine as I can test
    $id=$_POST[‘id’];
    if($id==1){
    echo “Selected item 1″;
    and it works fine.
    However, I can’t get any results to populate from my database. Do you know what I can do to continue debugging, or do you know what my problem could be? The sql query works fine in phpmyadmin, and the same query (with echo results) work fine in my index.php for the first option. As you can tell, this is very confusing!

    $sql = mysqli_query($db,”SELECT * FROM item_table WHERE type_id=’$id'”);
    while($row = mysqli_fetch_array($sql)){
    echo ”.$row[‘item_name’].”;
    }

    any advice would be appriciated! Cheers!

    1. I will suggest you that you just download my tutorial from the above download link and if you are using xampp then place the downloaded folder in it and make database connection changes and then test if it is working in your side or not. It should be working, make sure that you create a separate folder as i said, if you will try to use Ajax inside any other CMS may be it will not work, like WordPress have other requirements to work on Ajax, therefore first try my sample demo file on your host.

      1. Hi, Thank you for a really quick reply.
        Your demo seems to be working just fine. I tried using your demo as a starting point, changing your sql values to the ones in my database. Still no luck though! The query works just fine in index.php, but it seems I can’t even make a connection when accessing the database through ajax using my own credentials. I even tested the connection:
        if($con){
        echo ‘Connected’; };
        else {
        echo ‘Not Connected’>;
        If the database connected, when I select my first dropdown bar (that works perfectly fine), the dropdown bar will read either not connected, or connected. Each time the bar will always say that there is no connection being made. I have no idea how this is an issue as your demo worked perfectly fine! Thanks for your suggestions though!

        1. Well you can see that i made one db.php file and i call it on both pages, index.php and ajax.php so if your database connection is working fine on your index.php it should be working on your other page as well because this is same file. I think there may be some other issue, I prefer that you try to read my script again, may be you are facing issue because of some other reason.

  2. Hi friend,
    Can please give me a hint suppose you would like to display Country ID from the country Table in text Box. Demonstration with one single table

  3. hello Rehman, thank you for this article. I needed to change country for district and city for villages as it applies to my project and the script will not load the villages when i select a district. Please how can i get some help?

    1. This is not easy as you can not find data easily all list of streets of all countries, however you will need to create another table for street with fields name something like this street_id, street_name and city_id.
      And on ajax part also check if city is selected populate all street values in dependent field same as we did for city. Hope this help you.

      1. to also load the streets when a city is selected, can i add this to the ajax page?
        <?php
        include('db.php');
        if($_POST['id']){
        $id=$_POST['id'];
        if($id==0){
        echo "Select City”;
        }else{
        $sql = mysqli_query($con,”SELECT * FROM city WHERE country_id=’$id'”);
        while($row = mysqli_fetch_array($sql)){
        echo ”.$row

        [‘city_name’].”;
        }
        }
        }
        ?>
        <?php
        include('db.php');
        if($_POST['id']){
        $id=$_POST['id'];
        if($id==0){
        echo "Select Street”;
        }else{
        $sql = mysqli_query($con,”SELECT * FROM street WHERE city_id=’$id'”);
        while($row = mysqli_fetch_array($sql)){
        echo ”.$row

        [‘street_name’].”;
        }
        }
        }
        ?>

        Then what happen to the JQuery in the index page.
        Can you please rewrite this script to include street option?

        1. I would suggest you to use different field name in html select box and also in php script, if you use id for two select boxes then you will face duplicate issue, you can use city_id and check if city_id is set in PHP script then show street, you will also need to change it in Ajax script. Simply replace id with city_id on every call such as Ajax, Select box, and PHP script.

  4. Firstly, thank you very much for this tutorial, It is a really good job.
    Could you extend this solution to 3 steps?

    1. Step 3 is only database connection, as we always need to create database connection if we want using data from database, you can search about it in details in Google if you do not have any idea about database and its connection.

Leave a Reply

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