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 your 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 users table in the example.

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 –

  • The first dropdown contains department name, and
  • The another dropdown to show the users names which are filled with jQuery based on the department name selection from the first dropdown element.

Completed Code

<div class="container">
    <h1>Auto populate dropdown</h1>
    <div id="div_content">

        <div>Departments </div>
        <select id="sel_depart">
            <option value="0">- Select -</option>
            <option value="1">Finance</option>
            <option value="2">IT</option>
            <option value="3">Marketing</option>
            <option value="4">Operational</option>
            <option value="5">Sales</option>
            <option value="6">Staff</option>
        </select>
        <div class="clear"></div>

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

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 auto fill you can do this with any other element like TextBox, Textarea, etc. that you can fill with information according to input on another element.

Related Post

Spread the love

30 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

Leave a Reply

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