How to Auto populate dropdown with jQuery AJAX

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

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

This solves the problem but it is 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 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 new 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 and return the array in JSON format.

Completed Code

include "config.php";

$departid = $_POST['depart'];   // department id

$sql = "SELECT id,name FROM users WHERE department=".$departid;

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

$users_arr = array();

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 successfully 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

Select an option from the Department Dropdown.


7. Conclusion

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

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

Related Post

Spread the love
  • 3
  •  
  •  
  •  
  •  
  •  

63 Comments

  1. Eli said:

    thank you very much

    April 25, 2017
    Reply
  2. drafiko said:

    Hello. Great material, but don’t work for me.

    June 19, 2017
    Reply
    • Yogesh Singh said:

      What issue are you getting while implementing the script?

      I have updated the download link you can re-download and implement it.

      June 20, 2017
      Reply
      • drafiko said:

        Thank you. I load the script in XAMPP , PHP Version 7.0.18, php version 4.7.0, and the script don’t show any error, but don´t load values in the second box. Is it possible that it is the php version?

        June 20, 2017
        Reply
        • Yogesh Singh said:

          The mysql() function deprecated from PHP 7.

          I updated the tutorial according to mysqli().

          June 20, 2017
          Reply
          • drafiko said:

            Thank you Yogesh. Thanks a lot.

            June 20, 2017
  3. Deepak said:

    how to send data of dropdown menu in database using ajax and jquery

    June 22, 2017
    Reply
    • Yogesh Singh said:

      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.

      June 22, 2017
      Reply
  4. Alia said:

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

    June 22, 2017
    Reply
    • Yogesh Singh said:

      You can set an option selected from AJAX file.

      June 22, 2017
      Reply
      • Alia said:

        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.

        June 23, 2017
        Reply
        • Yogesh Singh said:

          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.

          June 23, 2017
          Reply
          • Alia said:

            Yes, this what exactly I want. Can you please mail me the code for this.
            Thank you.

            June 28, 2017
          • Yogesh Singh said:

            I have emailed you the codes.

            June 28, 2017
  5. imran said:

    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.

    June 23, 2017
    Reply
    • Yogesh Singh said:

      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.

      June 23, 2017
      Reply
      • imran said:

        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.

        June 23, 2017
        Reply
        • Yogesh Singh said:

          I created an example, where I get the user full name on the basis of entered username.

          Here, is the demo link.

          June 24, 2017
          Reply
          • imran said:

            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.

            June 24, 2017
          • Yogesh Singh said:

            Here, is the download link.

            I will try to publish a tutorial on this soon. Subscribe to our newsletter to get notified.

            June 24, 2017
          • imran said:

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

            June 24, 2017
          • imran said:

            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.

            June 25, 2017
          • imran said:

            Thank you very much now it is working properly.

            June 26, 2017
          • imran said:

            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.

            June 26, 2017
  6. Deepak Kumar Mohapatra said:

    Hello sir coluld you please send me the database table in sql format!

    June 25, 2017
    Reply
    • Yogesh Singh said:

      Table sql file is attached in the tutorial download.

      June 25, 2017
      Reply
  7. Alia said:

    Thank you soo much.

    June 30, 2017
    Reply
  8. Rick V said:

    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

    August 29, 2017
    Reply
    • Yogesh Singh said:

      I think there is some database related issue.

      For checking open getUsers.php file and replace $result = mysqli_query($con,$sql); with $result = mysqli_query($con,$sql) or die(mysqli_query($con)); to know the error.

      August 29, 2017
      Reply
  9. Akhil said:

    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

    August 30, 2017
    Reply
    • Yogesh Singh said:

      Yes, it is possible and you can make more than 2 dropdown elements dependent on other dropdown value.

      August 30, 2017
      Reply
  10. kiko said:

    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]

    October 3, 2017
    Reply
    • Yogesh Singh said:

      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.

      October 3, 2017
      Reply
  11. kent said:

    Thanks. This sample helped me a lot. I used input boxes in my app though.

    December 5, 2017
    Reply
  12. Md shammi said:

    I AM TRYING BUT NOT WORKING THIS CODE WHAT I DO. AJAX IS NOT RETURN VALUE

    December 14, 2017
    Reply
    • Yogesh Singh said:

      You can add following code
      error: function(data){
      console.log(“error : ” + JSON.stringify(data) );
      }
      with AJAX request to know is there any error in AJAX.

      December 15, 2017
      Reply
  13. Ishaq Mohammed said:

    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+”);
    }
    });

    });

    December 19, 2017
    Reply
  14. Ishaq Mohammed said:

    Great and very explanatory tutorial, thanks. And you are really supportive.

    December 21, 2017
    Reply
  15. Deepak said:

    This is amazing. Can you please send me the code.

    January 3, 2018
    Reply
    • Yogesh Singh said:

      Hi Deepak,
      Download link is available in the tutorial from where you can download.

      January 3, 2018
      Reply
  16. Sanjeev said:

    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.

    January 5, 2018
    Reply
  17. krlos said:

    Muchas Gracias. Me sirvió mucho…

    January 11, 2018
    Reply
  18. Enabs said:

    Thanks for the tuts, you are a life saver

    January 21, 2018
    Reply
  19. marco mameli said:

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

    April 8, 2018
    Reply
    • Yogesh Singh said:

      I not used department table in the tutorial. Directly created options in the department dropdown and use the selected option value for filter records.

      April 8, 2018
      Reply
  20. Do Phan Viet said:

    Thank your post. Your website so awesome! A lot of useful tuts there.

    April 23, 2018
    Reply
  21. Nagesh kumar H N said:

    Thanks a lot

    April 24, 2018
    Reply
  22. shruti said:

    please mail this code…

    May 2, 2018
    Reply
  23. Sashwat said:

    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 ?

    May 11, 2018
    Reply
    • Yogesh Singh said:

      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’

      May 11, 2018
      Reply
  24. Abingpj said:

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

    July 26, 2018
    Reply
  25. kitey said:

    nice tutorial but same question as above ? is it different if the first drop down has data populated from mysql?

    August 29, 2018
    Reply
    • Yogesh Singh said:

      The code will be the same in jQuery and AJAX.

      August 29, 2018
      Reply
  26. kitey said:

    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 🙂

    August 29, 2018
    Reply
    • Yogesh Singh said:

      I have updated the tutorial and populate the first dropdown values from MySQL table.

      If you still facing the issue then you can mail me the code at makitweb@gmail.com so I can check it.

      August 29, 2018
      Reply
  27. adi said:

    thank you very much

    November 18, 2018
    Reply

Leave a Reply

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