In this tutorial, you will learn how to create a dynamic dependent dropdown list using JavaScript, PHP, and MySQL. This feature enhances user experience by updating one dropdown list based on the selection made in another.



Dynamic Dependent Dropdown List Demo

What Is a Dynamic Dependent Dropdown List?

A Dynamic Dependent Dropdown List is an interactive, user-friendly feature that allows users to select options from a dropdown list based on the selection made in another dropdown list. For example, you might have a dropdown of countries and states. When the user selects a country in the first dropdown list, the second list will dynamically update to show only the states belonging to that country.

How Does It Work?

When a user chooses an option in the first dropdown, JavaScript triggers an AJAX request to a PHP script residing on the server. This PHP script queries the MySQL database to fetch relevant data for the secondary dropdown according to the initial selection. The JavaScript code then populates the secondary dropdown with the new set of options.

Steps to Create a Dynamic Dependent Dropdown List

Here's how you can create this feature:

Database Setup

You need to set up a MySQL database to store the data for the dynamic dependent dropdown list. Follow these steps to create the necessary database and table:

  1. Open your MySQL management tool, such as phpMyAdmin.
  2. Create a new database dropdown_list.
  3. Create a tbl_countries and insert some sample data into the table.
  4. After you've set up your tbl_countries table, create a tbl_states table to store the states corresponding to each country.

For example, if you are creating a country and state dropdown list, your SQL might look like this:

-- Create Database
CREATE DATABASE dropdown_list;

-- Use the Database
USE dropdown_list;

-- Create tbl_countries Table
CREATE TABLE `tbl_countries` (
  `country_code` char(2) NOT NULL,
  `country_name` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- Insert Data into tbl_countries
INSERT INTO tbl_countries (country_code, country_name) VALUES 
('IN', 'India'), 
('US', 'United States'), 
('GB', 'United Kingdom');

-- Create tbl_states Table
CREATE TABLE `tbl_states` (
  `state_code` char(2) DEFAULT '',
  `state_name` varchar(128) NOT NULL DEFAULT '',
  `country_code` char(2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- Insert Data into tbl_states
INSERT INTO tbl_states (state_code, state_name, country_code) VALUES 
('NY', 'New York', 'US'), 
('CA', 'California', 'US'), 
('TX', 'Texas', 'US'), 
('UP', 'Uttar Pradesh', 'IN'), 
('MH', 'Maharashtra', 'IN'), 
('BR', 'Bihar', 'IN');

Creating the HTML Form

Now, let's create the HTML form with two select elements—one for choosing the country and another for selecting the state.

<form>
    <label for="country">Country:</label>
    <select id="country" name="country" onchange="getStates(this.value)">
        <option value="">Select Country</option>
        <?php foreach($countries as $country){ ?>
        <option value="<?php echo $country['country_code'];?>"><?php echo $country['country_name'];?></option>
        <?php } ?>
    </select>

    <label for="state">State:</label>
    <select id="state" name="state" disabled>
        <option value="">Select State</option>
    </select>
</form>

Implementing JavaScript Functionality

Next, write the JavaScript code that will handle the dynamic behavior of the dropdown lists:

// JavaScript function to fetch and populate states based on the selected country
function getStates(country_code) {
    // Initialize XMLHttpRequest object
    var xhr = new XMLHttpRequest();

    // Configure GET request to fetch state data from the PHP script
    xhr.open("GET", "get_states.php?country_code=" + country_code, true);

    // Define callback function for handling state data once received
    xhr.onreadystatechange = function() {
        // Check if the request is complete and successful
        if (xhr.readyState === 4 && xhr.status === 200) {

            // Parse the JSON response to obtain state data
            var states = JSON.parse(xhr.responseText);

            // Access the state dropdown element
            var stateDropdown = document.getElementById("state");

            // Clear and set the default option for the state dropdown
            stateDropdown.innerHTML = "<option value=''>Select State</option>";
            
            // Enable the state dropdown for user interaction
            stateDropdown.disabled = false;

            // Loop through the state data to populate the state dropdown
            states.forEach(state => {
                var option = document.createElement("option");
                option.value = state.state_id;
                option.text = state.state_name;
                stateDropdown.appendChild(option);
            });
        }
    };

    // Send the GET request to fetch state data
    xhr.send();
}

PHP Code to Fetch Data

Finally, let's implement PHP code to fetch the states based on the selected country from MySQL and return it as a JSON response.

<?php
// Get config file
require("config.php"); 

// Get and sanitize the country ID from the GET request.
$countryId = filter_input(INPUT_GET, "country_code", FILTER_SANITIZE_STRING);

// Check if the countryId is empty after sanitization.
if (empty($countryId)) {
  die("Invalid country code.");
}

// Create the SQL query to retrieve states based on the country ID.
$sql = "SELECT state_code, state_name FROM tbl_states WHERE country_code = '$countryId'";

// Execute the query.
$result = mysqli_query($conn, $sql);

// Convert the result set to an array.
$states = mysqli_fetch_all($result, MYSQLI_ASSOC);

// Echo the JSON response.
echo json_encode($states);

// Close the database connection.
mysqli_close($conn);
?>

Conclusion

Dynamic dependent dropdown lists enhance the user experience by making web applications more interactive. Follow this guide to incorporate this feature into your projects easily.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram