Introduction
A dynamic dependent dropdown list allows the options in one dropdown to change based on the value selected in another dropdown.
For example, when a user selects a country, the second dropdown can automatically display the corresponding states. In this guide, we will create a dependent dropdown using HTML, PHP, MySQL, and AJAX.
The existing code and implementation steps are retained below.
Prerequisites
Before starting, make sure you have:
- A PHP-enabled web server.
- MySQL database access.
- jQuery available in the application.
- Basic knowledge of HTML, PHP, MySQL, and JavaScript.
- A database named
demoorlinuswith the required tables.
Implementation
Step 1: Create dropdown-ajax.php
Create a new file named:
dropdown-ajax.php
Create the MySQL connection inside the file:
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
mysql_connect($host, $user, $pass);
mysql_select_db('demo');
?>
Step 2: Create the MySQL Tables
Create the ls_countries and ls_states tables.
CREATE TABLE `ls_states` ( `state_id` int(11) NOT NULL, `name` varchar(30) NOT NULL, `country_id` int(11) NOT NULL DEFAULT '1', `status` int(11) NOT NULL COMMENT '1->active,0->deactive', PRIMARY KEY (`state_id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `ls_countries` ( `country_id` int(11) NOT NULL AUTO_INCREMENT, `sortname` varchar(3) NOT NULL, `name` varchar(150) NOT NULL, `phonecode` int(11) NOT NULL, `status` int(11) NOT NULL COMMENT '1->active,0->deactive', PRIMARY KEY (`country_id`)) ENGINE=InnoDB AUTO_INCREMENT=247 DEFAULT CHARSET=utf8
Step 3: Create the Dropdown Lists
Create two dropdown lists. The first dropdown displays the countries, while the second dropdown is populated dynamically based on the selected country.
<select onchange="fetch_select(this.value);">
<option>Select country</option>
<?php
$select=mysql_query("select * from ls_countries");
while($row=mysql_fetch_array($select))
{
echo "<option value=".$row['country_id'].">".$row['name']."</option>";
}
?>
</select>
<select id="new_select">
</select>
When a country is selected, the fetch_select() function is called with the selected country ID.
Step 4: Create the AJAX Function
Create the JavaScript function that sends the selected country value to fetch_data.php.
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("new_select").innerHTML=response;
}
});
}
The AJAX request sends the selected country ID to fetch_data.php. The response is then inserted into the second dropdown.
Step 5: Create fetch_data.php
Create a new file named:
fetch_data.php
This file receives the selected country ID, retrieves the corresponding states from MySQL, and returns them as dropdown options.
<?php
if(isset($_POST['get_option']))
{
$host = 'localhost';
$user = 'root';
$pass = '';
mysql_connect($host, $user, $pass);
mysql_select_db('demo');
$country_id = $_POST['get_option'];
$find=mysql_query("select * from ls_states where country_id='$country_id'");
while($row=mysql_fetch_array($find))
{
echo "<option>".$row['name']."</option>";
}
exit;
}
?>
Final Code
dropdown-ajax.php
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
mysql_connect($host, $user, $pass);
mysql_select_db('demo');
$select=mysql_query("select * from ls_countries");
while($row=mysql_fetch_array($select))
{
echo "<option value=".$row['country_id'].">".$row['name']."</option>";
}
?>
<html>
<head>
<source src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js" type="text/javascript">
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("new_select").innerHTML=response;
}
});
}
</head>
<body>
<select onchange="fetch_select(this.value);">
<option>Select country</option>
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
mysql_connect($host, $user, $pass);
mysql_select_db('linus');
$select=mysql_query("select * from ls_countries");
while($row=mysql_fetch_array($select))
{
echo "<option value=".$row['country_id'].">".$row['name']."</option>";
}
?>
</select>
<select id="new_select">
</select>
</body>
</html>
fetch_data.php
<?php
if(isset($_POST['get_option']))
{
$host = 'localhost';
$user = 'root';
$pass = '';
mysql_connect($host, $user, $pass);
mysql_select_db('linus');
$country_id = $_POST['get_option'];
$find=mysql_query("select * from ls_states where country_id='$country_id'");
while($row=mysql_fetch_array($find))
{
echo "<option>".$row['name']."</option>";
}
exit;
}
?>
Conclusion
A dynamic dependent dropdown is useful when the options in one field depend on another field. In this example, the country dropdown triggers an AJAX request, PHP retrieves the matching states from MySQL, and the results are displayed in the second dropdown without reloading the page.
The same approach can be extended to other dependent selections such as country → state → city, category → subcategory, or department → employee.
FAQs
1. What is a dependent dropdown?
A dependent dropdown is a dropdown whose options are dynamically loaded based on the value selected in another dropdown.
2. Why is AJAX used in this example?
AJAX allows the second dropdown to be updated dynamically without refreshing the entire page.
3. What does fetch_select() do?
The fetch_select() JavaScript function sends the selected country ID to fetch_data.php and places the returned state options into the second dropdown.
4. Where are the state values retrieved?
The state values are retrieved from the ls_states MySQL table using the selected country_id.
5. Can this approach be used for more than two dropdowns?
Yes. The same concept can be extended to multiple dependent dropdowns, such as country → state → city.
Related Articles
PHP Zip Directory Automatically Download
Learn how to create and automatically download ZIP archives of directories using PHP.
https://pheonixsolutions.com/blog/php-zip-directory-automatically-download-using/
Simple Form jQuery Validation with PHP
Learn how to implement form validation using jQuery and PHP for web applications.
https://pheonixsolutions.com/blog/simple-form-jquery-validation-php/
Talk to our experts
Looking for the right technology solution for your business? Our team of experts can help you with development, cloud, DevOps, design, and a wide range of other technology needs. Get in touch with our team here.
Thanks for sharing. This article is useful to learn Dependent Dropdown Using Ajax in PHP.