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.

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

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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
  7. 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
  8. 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
  9. 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