How to Auto populate dropdown with jQuery AJAX

Sometimes, we have a requirement to make another element dependent on another element selection.

For example, when you go for the Registration to the website when you select a country according to that State Dropdown is filled.

You can do this with 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 and this is not every user-friendly.

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

What in the Demonstration ?

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. Configuration
  2. HTML
  3. PHP
  4. jQuery
  5. Demo
  6. Conclusion

 

1. Configuration

Create a new PHP file (config.php). This file contains database connection. In this tutorial, we are using a tutorial database.

Completed Code

<?php

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

$con = mysql_connect($host, $user, $password) or die("Unable to connect");

// selecting database
$db = mysql_select_db($dbname, $con) or die("Database not found");

2. HTML

Creating two Dropdown elements one is for Department which contains department names and another is for users.

The users dropdown is filled with jQuery based on the first dropdown selection.

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>

3. PHP

Create a new getUsers.php file for fetching users based on department 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 = mysql_query($sql);

$users_arr = array();

while( $row = mysql_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);

4. jQuery

Sending AJAX request when the dropdown selected option is being changed.

Using the selected option value as data in AJAX request and on successfully callback filling <select id=”sel_user”> dropdown 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>");

                }
            }
        });
    });

});

5. Demo

Select an option from the Department Dropdown.


6. 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 fill with information according to input on another element.

Spread the love

Related Post

Be First to Comment

Leave a Reply

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