How to Auto populate dropdown with jQuery AJAX

Sometimes it requires auto-populate data on the element based on the selection of another element e.g. City names based on a state.

You can do this with only PHP but it required you to submit every time on selection.

This solves the problem but it is a little frustrating because it submits every time even if the selection is right or wrong.

For making it better you can use AJAX with jQuery that loads new data and removes the old one on each selection.

In the demonstration, I am creating a Department drop-down list, and based on the option selection show all existing users of that department on another Dropdown.

How to Auto populate dropdown with jQuery AJAX


Contents

  1. Table structure
  2. Configuration
  3. HTML
  4. PHP
  5. jQuery
  6. Demo
  7. Conclusion

1. Table structure

I am using 2 tables in the example –

department Table –

CREATE TABLE `department` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `depart_name` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

users Table –

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `email` varchar(80) NOT NULL,
  `department` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Create a config.php to define database connection.

Completed Code

<?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. HTML

Creating two Dropdown elements one –

  • Fetch records from department table and use to add <option> in <select id='sel_depart'>  and
  • Another dropdown shows the users names which are filled with jQuery based on the department name selection from the first dropdown element.

Completed Code

<?php 
include "config.php";
?>

<div>Departments </div>
       
<select id="sel_depart">
   <option value="0">- Select -</option>
   <?php 
   // Fetch Department
   $sql_department = "SELECT * FROM department";
   $department_data = mysqli_query($con,$sql_department);
   while($row = mysqli_fetch_assoc($department_data) ){
      $departid = $row['id'];
      $depart_name = $row['depart_name'];
      
      // Option
      echo "<option value='".$departid."' >".$depart_name."</option>";
   }
   ?>
</select>
<div class="clear"></div>

<div>Users </div>
<select id="sel_user">
   <option value="0">- Select -</option>
</select>

4. PHP

Create a new getUsers.php file.

Fetching users based on department selection from the users table.

Initialize $users_arr Array with userid and name.

Return $users_arr Array in JSON format.

Completed Code

<?php 

include "config.php";

$departid = 0;

if(isset($_POST['depart'])){
   $departid = mysqli_real_escape_string($con,$_POST['depart']); // department id
}

$users_arr = array();

if($departid > 0){
   $sql = "SELECT id,name FROM users WHERE department=".$departid;

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

   while( $row = mysqli_fetch_array($result) ){
      $userid = $row['id'];
      $name = $row['name'];

      $users_arr[] = array("id" => $userid, "name" => $name);
   }
}
// encoding array to json format
echo json_encode($users_arr);

5. jQuery

Sending AJAX request when an option selected from the first drop-down. Pass the selected option value as data and on successful callback fill <select id='sel_user'> with response.

Completed Code

$(document).ready(function(){

    $("#sel_depart").change(function(){
        var deptid = $(this).val();

        $.ajax({
            url: 'getUsers.php',
            type: 'post',
            data: {depart:deptid},
            dataType: 'json',
            success:function(response){

                var len = response.length;

                $("#sel_user").empty();
                for( var i = 0; i<len; i++){
                    var id = response[i]['id'];
                    var name = response[i]['name'];
                    
                    $("#sel_user").append("<option value='"+id+"'>"+name+"</option>");

                }
            }
        });
    });

});

6. Demo

View Demo


7. Conclusion

In the example, I used dropdown element for autofill but you can do this with any other element like TextBox, Textarea, etc. that you can fill with information according to input on another element.

You can view this tutorial to know to auto-populate dropdown with PDO and PHP.

If you found this tutorial helpful then don't forget to share.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

131 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

Leave a Comment