How to Auto populate dropdown with jQuery AJAX

When working with large datasets, auto-populating dropdown lists is a common requirement in web development.

With the help of jQuery AJAX, it’s possible to dynamically fill dropdown lists with data from a server in response to user input.

A common use case of this feature is when selecting a country, state, and city. According to the country selection related state list populates, followed by a list of cities within the selected state.

It enables users to quickly choose their location from a list of options and can enhance the user experience by requiring less manual input.

In this tutorial, I show how you can use jQuery AJAX and PHP to autopopulate dropdown with MySQL database data.

How to Auto populate dropdown with jQuery AJAX


Table of Content

  1. Create Tables
  2. Setting up the Database connection
  3. Create HTML Layout
  4. AJAX file – Return data for autopopulate
  5. Creating the jQuery AJAX script to load data
  6. Demo
  7. Conclusion

1. Create Tables

I am using 3 tables in the example –

countries table (Store countries) –

CREATE TABLE `countries` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(80) NOT NULL
);

states table (Store states of the countries) –

CREATE TABLE `states` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(80) NOT NULL,
  `country_id` int(11) NOT NULL
);

cities table (Store cities of the states) –

CREATE TABLE `cities` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(80) NOT NULL,
  `state_id` int(11) NOT NULL
);

2. Setting up the Database connection

To define the database connection, create a config.php file.

<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

3. Create HTML Layout

To get started,  create three dropdowns using the <select> element.

The first dropdown will allow users to select their country. Fetch all records from the countries table and loop them to add each country as an <option> to the dropdown.

The second dropdown will be initially empty and will be used to select the state within the selected country. We’ll use jQuery AJAX to dynamically load the state data when a user selects a country from the first dropdown.

Similarly, the third dropdown will also be initially empty and will be used to select the city within the selected state. We’ll again use jQuery AJAX to dynamically load the city data when a user selects a state from the second dropdown.

<?php 
include "config.php";
?>
<div >
     <?php 
     // Fetch all countries
     $sql = "select * from countries";
     $result = mysqli_query($con,$sql);
     ?>
     <!-- Country Dropdown -->
     <div>Country </div>
     <select id="sel_country">
          <option value="0">- Select Country -</option>
          <?php 
          while($row = mysqli_fetch_assoc($result)){
                $country_id = $row['id'];
                $country_name = $row['name'];

                echo "<option value='".$country_id."' >".$country_name."</option>";
          }
          ?>
     </select>
     <br>

     <!-- State Dropdown -->
     <div>State </div>
     <select id="sel_state">
           <option value="0">- Select State -</option>
     </select>
     <br>

     <!-- City Dropdown -->
     <div>City </div>
     <select id="sel_city">
           <option value="0">- Select City -</option>
     </select>

</div>

4. AJAX file – Return data for autopopulate

To handle AJAX requests, create a separate file called ajaxfile.php. This file handles two types of requests –

  • $request == ‘getCountryStates’ (Return country state list)

To obtain the user-selected country ID, read the POST data. Then, we’ll fetch the records from the states table where the country_id matches the selected country.

Loop through the fetched records and store each state’s ID in the $response['id'] variable and its name in $response['name'] variable. Finally, return the $response array in JSON format.

  • $request == ‘getStateCities’ (Return state city list)

Similarly, read the POST data to get the state ID that was selected by the user. Then, fetch the records from the cities table where the state_id matches the selected state.

Loop through the fetched records and store each city’s ID in the $response['id'] variable and its name in $response['name'] variable. Finally, we’ll return the $response array in JSON format.

<?php

include "config.php";

$request = '';

if(isset($_POST['request'])){
     $request = $_POST['request'];
}

// Fetch state list by country_id
if($request == 'getCountryStates'){

     $country_id = 0;
     if(isset($_POST['country_id']) && is_numeric($_POST['country_id'])){
           $country_id = $_POST['country_id'];
     }

     $sql = "select * from states where country_id=".$country_id;
     $stateData = mysqli_query($con,$sql);

     $response = array();
     while($state = mysqli_fetch_assoc($stateData)){
           $response[] = array(
                "id" => $state['id'],
                "name" => $state['name']
           );
     }

     echo json_encode($response);
     exit;
}

// Fetch city list by state_id
if($request == 'getStateCities'){

     $state_id = 0;
     if(isset($_POST['state_id']) && is_numeric($_POST['state_id'])){
           $state_id = $_POST['state_id'];
     }

     $sql = "select * from cities where state_id=".$state_id;
     $cityData = mysqli_query($con,$sql);

     $response = array();
     while($city = mysqli_fetch_assoc($cityData)){
           $response[] = array(
                 "id" => $city['id'],
                 "name" => $city['name']
           );
     }

     echo json_encode($response);
     exit;
}

5. Creating the jQuery AJAX script to load data

Define change event on <select id='sel_country'> and <select id='sel_state'> element.

  • Country selection change –

When the country selection changes, read the selected option value and assign it to the country_id variable. Then empty the state and city dropdowns.

Next, send an AJAX POST request to ajaxfile.php and pass {request:'getCountryStates',country_id:country_id} as the data. Set the dataType to 'json'. On successful callback, loop through the response data and create new <option> elements for the state dropdown.

  • State selection change –

Similarly, when the state selection changes, read the selected option value and assign it to the state_id variable. Then empty the city dropdown.

Next, send an AJAX POST request to ajaxfile.php and pass {request:'getStateCities',state_id:state_id} as the data. Set the dataType to 'json'. On successful callback, loop through the response data and create new <option> elements for the city dropdown.

$(document).ready(function(){

     // Country change
     $("#sel_country").change(function(){

          // Selected country id
          var country_id = $(this).val();

          // Empty state and city dropdown
          $('#sel_state').find('option').not(':first').remove();
          $('#sel_city').find('option').not(':first').remove();

          // Fetch country states
          $.ajax({
               url: 'ajaxfile.php',
               type: 'post',
               data: {request:'getCountryStates',country_id:country_id},
               dataType: 'json',
               success:function(response){

                     var len = response.length;

                     // Add data to state dropdown
                     for( var i = 0; i<len; i++){
                           var state_id = response[i]['id'];
                           var state_name = response[i]['name'];

                           $("#sel_state").append("<option value='"+ state_id +"' >"+ state_name +"</option>");

                     }
               }
          });
     });

     // State change
     $('#sel_state').change(function(){

          // Selected state id
          var state_id = $(this).val();

          // Empty city dropdown
          $('#sel_city').find('option').not(':first').remove();

          // Fetch state cities
          $.ajax({
               url: 'ajaxfile.php',
               type: 'post',
               data: {request:'getStateCities',state_id:state_id},
               dataType: 'json',
               success:function(response){

                     var len = response.length;

                     // Add data to city dropdown
                     for( var i = 0; i<len; i++){
                           var city_id = response[i]['id'];
                           var city_name = response[i]['name'];

                           $("#sel_city").append("<option value='"+ city_id +"' >"+ city_name +"</option>");

                     }
               }
          });

     });
});

6. Demo

View Demo


7. Conclusion

By utilizing the power of jQuery AJAX, you can make server-side calls to retrieve relevant data from the database and populate dropdowns on the client side in real time. This allows users to select the appropriate data quickly and easily without the need for manual input or page refreshes.

Dynamic-dependent dropdowns are a crucial feature in many web applications, and by mastering this technique, you’ll be able to improve your users’ experience and create more efficient and user-friendly forms. So go ahead, give it a try, and start implementing dynamic-dependent dropdowns in your web application project!

You can also view this tutorial to learn how to auto-populate dropdown with PDO and PHP.

If you found this tutorial helpful then don't forget to share.

133 thoughts on “How to Auto populate dropdown with jQuery AJAX”

    • I don’t exactly get your question?

      If you want to fetch data based on the dropdown value selection then you need to pass that value as data in $.ajax and select records from AJAX file and return it.

      That I am already doing in the tutorial.

      Reply
  1. How to make the dropdown value selected (second dropdown) so that if we need to edit that value, it appears in the dropdown.

    Reply
      • I tried to set an option selected but it didn’t work for me. Can you give some example or show the same selected text in above example of your’s. It will be a great help for me.
        Thank you in advance.

      • I think you want to store the previously selected user value and want to show selected when a department name is again selected.

        For this, you can use JavaScript Object or Array to store selected user option by depart in it. Next time when that department again selected then get value from the variable and check it on AJAX successfully callback if it gets matched then set an option selected with jQuery.

        Here is the demo link.

  2. It is working properly. but i need to search by text box for instance if i write department name in one text box then in other text box user name will auto display kindly resolve this problem immediately.

    Reply
    • You need to define keyup event on the textbox and pass the entered value as data in AJAX request.

      From the PHP file (AJAX) select user records on the department name basis.

      Reply
      • i need a full program of text box searching and result display in textbox with ajax php jquery.do u have any radimade code of that program.take example of biodata.when i enter the name the whole information will be displayed on the textboxes on the screen.

      • Thank you very much it is correct what i need that search by textbox display value in to another text box. But kindly send me the code so i can attach it with my code.

      • i am in great hurry if u send me the textbox searching on my emailbox immediately.thanks for ur immediate response.

      • Thanks . I have receive your textbox searching code but in demo it is working properly but the code which you link me for download that is not working.Means after writing username the fullname is not searching.kindly resolve it immediately.

      • Kindly send me the invoice in grid form where add,delete,edit,search,pdf,print,csv all the option is present.The format i have send you before where we select itemid the itemname will automatically display.record should be save in database.

  3. For some reason, when I download your code and I run it on my domain, it does not populate the second select when choosing a first option. I do have the latest PHP 7 installed. And Mysql users table has been filled with your data.. Do you have an idea why? or should I install PHP 5.6 ? or is there another reason.. Thanks again

    Reply
  4. Hai… Great tutorial ,
    is it possible to do the same with 3 drop down and fetch the value from 3 different tables using ?
    If yes it will be very much helpful for me
    Thank you

    Reply
  5. How can i load content via ajax after selecting from the dropdown?
    Basically we have 2 dependent dropdown, so after the user select the dropdown i want to load content for the selected dropdown.
    Sample
    [chair][material]-[whill show content of all chair with selected material in html]

    Reply
    • Hi kiko,
      In the tutorial example, I am auto filling the single user dropdown list when item got selected from the department drop-down. Similarly, if there is another dropdown element which is dependent on the first autofill dropdown then require binding the change event on the first drop-down element and fill data on the dependent dropdown with AJAX response.

      Reply
  6. Thanks very much that was really helpful and it works.
    But when I try this on dynamically generated input boxes(dynamic Add/remove text boxes) of which the first one is autocomplete with json, there is a problem that it fills all the generated textboxes with the auto-filled data. But I need it to work one by one, if you got y point.
    Here is my complete script

    $(document).ready(function(){

    $(document).on(‘click’, ‘.add’, function(){
    var html = ”;
    html += ”;
    html += ”;
    html += ”;
    html += ‘ semester ‘;
    html += ”;
    html += ”;

    $(‘#item_table’).append(html);

    $(function() {
    $( ‘.item_name’ ).autocomplete({ // here the ‘.’ on .item_name tells that it is the name of the field to use the id ‘#’ is used
    source: ‘autocomplete_search.php’
    });

    $(‘.item_name’).keyup(function(){
    var uname = $(this).val();

    $.ajax({
    url: ‘getUsers2.php’,
    type: ‘post’,
    data: {username:uname },
    dataType: ‘json’,
    success:function(response){

    var len = response.length;

    $(‘.item_section’).val(”);
    for( var i = 0; i<len; i++){
    var id = response[i]['id'];
    var name = response[i]['name'];

    $('.item_section').val(name);

    }
    }
    });
    });

    });

    });

    $(document).on('click', '.remove', function(){
    $(this).closest('tr').remove();
    });

    $('#insert_form').on('submit', function(event){ // here the '#' is used to identify id of the form
    event.preventDefault();
    var error = '';
    $('.item_name').each(function(){
    var count = 1;
    if($(this).val() == '')
    {
    error += "Enter Student Name at “+count+” Row”;
    return false;
    }
    count = count + 1;
    });

    $(‘.item_quantity’).each(function(){
    var count = 1;
    if($(this).val() == ”)
    {
    error += “Enter amount at “+count+” Row”;
    return false;
    }
    count = count + 1;
    });

    $(‘.item_unit’).each(function(){
    var count = 1;
    if($(this).val() == ”)
    {
    error += “Select type at “+count+” Row”;
    return false;
    }
    count = count + 1;
    });
    var form_data = $(this).serialize();
    if(error == ”)
    {
    $.ajax({
    url:”insert.php”,
    method:”POST”,
    data:form_data,
    success:function(data)
    {
    if(data == ‘ok’)
    {
    $(‘#item_table’).find(“tr:gt(0)”).remove();
    $(‘#error’).html(‘ successfully completed’);
    }
    }
    });
    }
    else
    {
    $(‘#error’).html(”+error+”);
    }
    });

    });

    Reply
  7. Hi Yogesh,

    I managed to create a dynamic second dropdown (dd) menu following your example. It is working fine. I have used DB table data to populate the 2 dds.

    However, I would like to provide the same set of dd more than once, in the same form.

    What modification need to be done to the ajax function so that it can be used multiple times?
    $(“#sel_depart”).change(function(){
    I have used the ‘id’ of the first dd as item1, item2, item3 and so on. It tried to create a loop using php but that messed up the function..!! 🙁
    The results generated from the set of dd1 and dd2 will be inserted in another table as part of data entry process.
    Any suggestion/ideas will be highly appreciated.

    Reply
  8. I don’t see the “department” table.
    I suppose it’s missing in the compressed file to download.
    Am I wrong?

    Reply
  9. Thank you for this example. I want to make a form where choice in 2 drop down lists will populate a third drop down list. That is, the 3rd drop down list will depend on the choices made in the first 2. The sql query will be something like “SELECT item WHERE item1=3 AND item2=5” . The results will go into third select list.
    Can you please show me what changes are to be made ?

    Reply
    • Hi Sashwat,
      Define change event on the 2nd dropdown and pass the selected values of the 1st and 2nd dropdown in the AJAX request to fetch records for the 3rd dropdown.
      E.g.
      SELECT * FROM users WHERE country=’IN’ and state=’BPL’

      Reply
  10. Nice tutorial, Thank you sir,…
    What if the 1st dropdown list are populated from database???
    what jquery method or function that i will use for the script code??

    Reply
  11. thanks for the reply

    just not what I needed to hear 🙁 cant get it to pull the data into the 2nd drop down, 1st drop down populates fine from MySQL , but on change of that dropdown 2nd doesn’t pull, the query is fine as tested it without the WHERE department=”.$departid;

    maybe a beer and break will give me more inspiration 🙂

    Reply
  12. This works great! Thank you. I am using this when i must add information. But what about editing? How can i set default option value? I cant do this on (html), it must be set on .

    Reply
  13. hi
    the second select don’t work and in getUsers.php it show the following error
    Notice: Undefined index: dept in C:\xampp\htdocs\universite4\getUsers.php on line 4
    how to solve this problem.

    Reply
  14. Hi sir,

    I have successfully created three dropdowns but after selecting an option in the third dropdown I would like to display related information on the page like suppose in the first dropdown we have branches of a college and then in the second we have semesters and after clicking a semester option, I would like to display the students information in that semester on the page in a table. Can u plz help me out with it? Is there any tutorial for this?

    Plz kindly reply as early as possible.

    Thanx.

    Reply
    • Hi Shoeb,
      You need to define change event on the third dropdown and send an AJAX request to fetch records and pass the required parameters. From the AJAX file return the data which you want to display.

      Reply
  15. Thank you so much for this, once i figured out a few variables issues it works perfect for my site and is exactly what i need. However I do have a problem, I need to extract the IDs from both drop downs to populate a mySQL table. How would I go about getting the IDs from the drop down selections?

    Reply
  16. This works great except if for example I have a cat and sub_cat field. When I go back to edit the item I can get the cat field to populate, but don’t know how to get auto load the second box. IE let say I go back and deptid is 5. How do you load that as soon as page loads?

    Reply
    • Hi Jerry,
      You can either send AJAX request to fetch data for the second dropdown on page load based on the first dropdown value or use can just fetch data according to the first dropdown value for the second dropdown using PHP and display it.

      Reply
  17. Notice: Undefined index: request in C:\xampp\htdocs\autocomplete\getDetails.php on line 6
    $row[‘id’],”label”=>$row[‘username’]);
    }

    // encoding array to json format
    echo json_encode($response);
    exit;
    }

    // Get details
    if($request == 2){
    $userid = $_POST[‘userid’];
    $sql = “SELECT * FROM users WHERE id=”.$userid;

    $result = mysqli_query($con,$sql);

    $users_arr = array();

    while( $row = mysqli_fetch_array($result) ){
    $userid = $row[‘id’];
    $fullname = $row[‘fname’].” “.$row[‘lname’];
    $email = $row[’email’];
    $age = $row[‘age’];
    $salary = $row[‘salary’];

    $users_arr[] = array(“id” => $userid, “name” => $fullname,”email” => $email, “age” =>$age, “salary” =>$salary);
    }

    // encoding array to json format
    echo json_encode($users_arr);
    exit;
    }
    ?>
    Pl help me

    Reply
  18. A Huge thanks
    using jscript and ajax to populate the second dropdown with sql data with a few mods.
    A lot of posts arround on the internet but this was the only one that helped – clear and not overly complicated

    Reply
  19. Thank you,but in par 4:i can’t understand “depart” in this command:
    $departid = $_POST[‘depart’]; // department id
    In code where use it?(depart)

    Reply
  20. Thank you,but I have some problems,i can’t understand command :
    $departid = $_POST[‘depart’]; // department id part 4,where use depart in code?

    Reply
  21. Thank you so much for the clear tutorial, I was able to integrate for my school project however when i do up the third dropdown it says its undefined. How i can resolve it ?

    Reply
  22. hii bro lot of thanks to you..
    i think some small correction in getUsers.php page
    $sql = “SELECT id,name FROM users WHERE department=”.$departid; this line didn’t work.
    please change to $sql = “SELECT id,name FROM users WHERE department=”$departid”;

    Reply
  23. i want a situation like the first dropdown has 1st value as default value and 2nd drop down has its respective default values in its dropdown.what changes should be there in ajax and js files. Urgent

    Reply
  24. Hi! This is amazing I really wanna thank you but i got a question
    My first dropdown has 2 values joined from my db: id and name, since the user
    has to see the company ID and the NAME
    So how do I get id and send it at the post so it can compare ?
    My dropdown company has this
    Company:
    Select Company
    $company_name =”[“.$type[‘id’].”] “.$type[‘name’];
    echo”.$company_name.”;
    }
    How do I select ONLY the ID from my dropdown and send it in the POST ?

    Reply
  25. Super cool I have searched a lot to do this work. All did very difficult someone’s code didn’t work. But your works. Thank and Thumsup from Pakistan. You are life saver.

    Reply
  26. I am trying to use this code, but my drop down is not getting populated with data. How ever the data is displayed on the page

    Reply
  27. hello sir, I’ve tried the code but it didn’t work for me, I’m not getting any error messages and my database data are in one table and not two tables like yours. To be honest I don’t have knowledge on jquery and tried my best to understand yours to implement it but I need to do this and your code seemed the simplest one. can you help me through it?

    Reply
  28. Hi Yogesh,

    Your “How to Auto populate dropdown with jQuery AJAX” example is just what I am looking for. I trust the jQuery code is placed in the html file as javascript?

    Many thanks,
    Ira
    (I’m am JS & AJAX newbie!)

    Reply
  29. Hi
    how to store data in database and view this data on different page
    because only id of this particular menu selected in option

    Reply
  30. Hello, Thanks for your code. how do can I post back data into select box? ie: if I send data to server and server back any error, I need to load and select data in post back.

    Reply
  31. Dear Yogesh,

    I have downloaded the demo files to my computer and as per instructions I have done following:
    Updated the database info in Config.php file.
    Created the relevant tables in database successfully.
    yet i cannot see the code working on your own files even. drop downs are showing but none of the data is populated in either drop downs in your own files. any thoughts please.

    Reply
  32. Hi Yogesh

    I have configured your script for my database since I use only one database and it worked [or perfectly.

    Now my consilta is the following. I need these dropdowns to be part of a form that must be completed and submitted. This script can I put it inside a form and send it once completed?

    Thanks

    Reply
  33. But HOW do you pass a post value to the php form to parse the JSON? I’m tearing my hair out over here trying to get this to work and it doesn’t.

    Reply
  34. Hi Yogesh.
    The code works fine, thanks for the excellent tutorial.
    How do I get the boxes to stay populated with the chosen values after I submit the form? After submitting the textboxes lose their chosen values. Thanks.

    Reply

Leave a Reply to Alia Cancel reply