When working with large datasets, auto-populating dropdown lists is a common requirement in web development.
With the help of jQuery AJAX, it’s possible to dynamically fill dropdown lists with data from a server in response to user input.
A common use case of this feature is when selecting a country, state, and city. According to the country selection related state list populates, followed by a list of cities within the selected state.
It enables users to quickly choose their location from a list of options and can enhance the user experience by requiring less manual input.
In this tutorial, I show how you can use jQuery AJAX and PHP to autopopulate dropdown with MySQL database data.
Table of Content
- Create Tables
- Setting up the Database connection
- Create HTML Layout
- AJAX file – Return data for autopopulate
- Creating the jQuery AJAX script to load data
- Demo
- Conclusion
1. Create Tables
I am using 3 tables in the example –
countries table (Store countries) –
CREATE TABLE `countries` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `name` varchar(80) NOT NULL );
states table (Store states of the countries) –
CREATE TABLE `states` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `name` varchar(80) NOT NULL, `country_id` int(11) NOT NULL );
cities table (Store cities of the states) –
CREATE TABLE `cities` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `name` varchar(80) NOT NULL, `state_id` int(11) NOT NULL );
2. Setting up the Database connection
To define the database connection, create a config.php
file.
<?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. Create HTML Layout
To get started, create three dropdowns using the <select>
element.
The first dropdown will allow users to select their country. Fetch all records from the countries
table and loop them to add each country as an <option>
to the dropdown.
The second dropdown will be initially empty and will be used to select the state within the selected country. We’ll use jQuery AJAX to dynamically load the state data when a user selects a country from the first dropdown.
Similarly, the third dropdown will also be initially empty and will be used to select the city within the selected state. We’ll again use jQuery AJAX to dynamically load the city data when a user selects a state from the second dropdown.
<?php include "config.php"; ?> <div > <?php // Fetch all countries $sql = "select * from countries"; $result = mysqli_query($con,$sql); ?> <!-- Country Dropdown --> <div>Country </div> <select id="sel_country"> <option value="0">- Select Country -</option> <?php while($row = mysqli_fetch_assoc($result)){ $country_id = $row['id']; $country_name = $row['name']; echo "<option value='".$country_id."' >".$country_name."</option>"; } ?> </select> <br> <!-- State Dropdown --> <div>State </div> <select id="sel_state"> <option value="0">- Select State -</option> </select> <br> <!-- City Dropdown --> <div>City </div> <select id="sel_city"> <option value="0">- Select City -</option> </select> </div>
4. AJAX file – Return data for autopopulate
To handle AJAX requests, create a separate file called ajaxfile.php
. This file handles two types of requests –
- $request == ‘getCountryStates’ (Return country state list)
To obtain the user-selected country ID, read the POST data. Then, we’ll fetch the records from the states
table where the country_id
matches the selected country.
Loop through the fetched records and store each state’s ID in the $response['id']
variable and its name in $response['name']
variable. Finally, return the $response
array in JSON format.
- $request == ‘getStateCities’ (Return state city list)
Similarly, read the POST data to get the state ID that was selected by the user. Then, fetch the records from the cities
table where the state_id
matches the selected state.
Loop through the fetched records and store each city’s ID in the $response['id']
variable and its name in $response['name']
variable. Finally, we’ll return the $response
array in JSON format.
<?php include "config.php"; $request = ''; if(isset($_POST['request'])){ $request = $_POST['request']; } // Fetch state list by country_id if($request == 'getCountryStates'){ $country_id = 0; if(isset($_POST['country_id']) && is_numeric($_POST['country_id'])){ $country_id = $_POST['country_id']; } $sql = "select * from states where country_id=".$country_id; $stateData = mysqli_query($con,$sql); $response = array(); while($state = mysqli_fetch_assoc($stateData)){ $response[] = array( "id" => $state['id'], "name" => $state['name'] ); } echo json_encode($response); exit; } // Fetch city list by state_id if($request == 'getStateCities'){ $state_id = 0; if(isset($_POST['state_id']) && is_numeric($_POST['state_id'])){ $state_id = $_POST['state_id']; } $sql = "select * from cities where state_id=".$state_id; $cityData = mysqli_query($con,$sql); $response = array(); while($city = mysqli_fetch_assoc($cityData)){ $response[] = array( "id" => $city['id'], "name" => $city['name'] ); } echo json_encode($response); exit; }
5. Creating the jQuery AJAX script to load data
Define change event on <select id='sel_country'>
and <select id='sel_state'>
element.
- Country selection change –
When the country selection changes, read the selected option value and assign it to the country_id
variable. Then empty the state and city dropdowns.
Next, send an AJAX POST request to ajaxfile.php
and pass {request:'getCountryStates',country_id:country_id}
as the data. Set the dataType
to 'json'
. On successful callback, loop through the response
data and create new <option>
elements for the state dropdown.
- State selection change –
Similarly, when the state selection changes, read the selected option value and assign it to the state_id
variable. Then empty the city dropdown.
Next, send an AJAX POST request to ajaxfile.php
and pass {request:'getStateCities',state_id:state_id}
as the data. Set the dataType
to 'json'
. On successful callback, loop through the response
data and create new <option>
elements for the city dropdown.
$(document).ready(function(){ // Country change $("#sel_country").change(function(){ // Selected country id var country_id = $(this).val(); // Empty state and city dropdown $('#sel_state').find('option').not(':first').remove(); $('#sel_city').find('option').not(':first').remove(); // Fetch country states $.ajax({ url: 'ajaxfile.php', type: 'post', data: {request:'getCountryStates',country_id:country_id}, dataType: 'json', success:function(response){ var len = response.length; // Add data to state dropdown for( var i = 0; i<len; i++){ var state_id = response[i]['id']; var state_name = response[i]['name']; $("#sel_state").append("<option value='"+ state_id +"' >"+ state_name +"</option>"); } } }); }); // State change $('#sel_state').change(function(){ // Selected state id var state_id = $(this).val(); // Empty city dropdown $('#sel_city').find('option').not(':first').remove(); // Fetch state cities $.ajax({ url: 'ajaxfile.php', type: 'post', data: {request:'getStateCities',state_id:state_id}, dataType: 'json', success:function(response){ var len = response.length; // Add data to city dropdown for( var i = 0; i<len; i++){ var city_id = response[i]['id']; var city_name = response[i]['name']; $("#sel_city").append("<option value='"+ city_id +"' >"+ city_name +"</option>"); } } }); }); });
6. Demo
7. Conclusion
By utilizing the power of jQuery AJAX, you can make server-side calls to retrieve relevant data from the database and populate dropdowns on the client side in real time. This allows users to select the appropriate data quickly and easily without the need for manual input or page refreshes.
Dynamic-dependent dropdowns are a crucial feature in many web applications, and by mastering this technique, you’ll be able to improve your users’ experience and create more efficient and user-friendly forms. So go ahead, give it a try, and start implementing dynamic-dependent dropdowns in your web application project!
You can also view this tutorial to learn how to auto-populate dropdown with PDO and PHP.
If you found this tutorial helpful then don't forget to share.
thanks a lot bro
thank you very much
Hello. Great material, but don’t work for me.
how to send data of dropdown menu in database using ajax and jquery
How to make the dropdown value selected (second dropdown) so that if we need to edit that value, it appears in the dropdown.
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.
Hello sir coluld you please send me the database table in sql format!
Thank you soo much.
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
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
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]
Thanks. This sample helped me a lot. I used input boxes in my app though.
I AM TRYING BUT NOT WORKING THIS CODE WHAT I DO. AJAX IS NOT RETURN VALUE
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+”);
}
});
});
Great and very explanatory tutorial, thanks. And you are really supportive.
This is amazing. Can you please send me the code.
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.
Muchas Gracias. Me sirvió mucho…
Thanks for the tuts, you are a life saver
I don’t see the “department” table.
I suppose it’s missing in the compressed file to download.
Am I wrong?
Thank your post. Your website so awesome! A lot of useful tuts there.
Thanks a lot
please mail this code…
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 ?
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??
nice tutorial but same question as above ? is it different if the first drop down has data populated from mysql?
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 🙂
thank you very much
thank you very much for your guidance
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 .
its not working inside modal bootsrap 4.
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.
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.
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?
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?
Thank you very much.
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
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
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)
Thank you,but I have some problems,i can’t understand command :
$departid = $_POST[‘depart’]; // department id part 4,where use depart in code?
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 ?
i tried it, why it returns a jsonparse error?
Hi!
I am trying to achieve similar thing using Angular. Can you help me proceed in it?
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”;
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
Perfect.
hello
how to use this in wordpress i have 2 taxonomy for my custom post type i want to display terms according to selected value
how to use the jQuery chain dropdown, used CakePHP 3.x
its showing undefined error if I m using it for other tables
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 ?
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.
i’m sory
how to add 1 more kriteria
Really helpfull code thank you so mutch for sharing am using your code at my site
I have a country and city related dropdown list.
I want to display the result(in table format) in different page when user click city
In PHP
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
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?
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!)
Hi
how to store data in database and view this data on different page
because only id of this particular menu selected in option
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.
Thanks for your esteemed work of code to fulfill our requirement.
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.
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
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.
Hi Yogesh.
The code works fine, thanks for the excellent tutorial.
How do I get the boxes to stay populated with the chosen values after I submit the form? After submitting the textboxes lose their chosen values. Thanks.
Thank you