Three interlinked dropdown listbox using Ajax & PHP

Three linked dropdown boxes for country, state and city
AJAX updates the state and city options when you change a country or state, without reloading the entire page. The demonstration uses PHP, PDO, a sample MySQL table and modern browser JavaScript.

You must read how options are added to a listbox in JavaScript. You can check how a default option is kept selected while adding options.

The basic two dropdown list ( ajax ) already explained here. We will further extend this script to make it three linked dropdown listbox.

This example has three lists: country, state and city. All options come from the student5 sample table, which includes those three columns. Download the SQL dump and runnable scripts below, and import the sample table only into a local test database.

You can also build dependent lists with jQuery. This example uses native JavaScript for the AJAX requests.
Tutorial with Demo on using Three linked dropdown list - JQuery

First dropdown list: Country

The first select box gets its countries from student5. In the live demo, PHP reads the distinct country codes using PDO and escapes each value before putting it in an HTML option. The shared database connection is available through ../include/z_db1.php; the downloadable standalone version uses config.php instead.

<label for="ajax-dd3-country">Country</label>
<select name="country" id="ajax-dd3-country" required>
    <option value="">Select a country</option>
    <?php
    require '../include/z_db1.php';
    $countries = $dbo->query('SELECT DISTINCT country FROM student5 ORDER BY country')->fetchAll(PDO::FETCH_COLUMN);
    foreach ($countries as $item) {
        $safeCountry = htmlspecialchars((string) $item, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
        echo '<option value="' . $safeCountry . '">' . $safeCountry . '</option>';
    }
    ?>
</select>

SQL DISTINCT prevents duplicate country codes from appearing. The dropdown uses three-letter country codes because that is how the sample table stores its data.

Second dropdown list: State

When a country changes, JavaScript clears both dependent lists and requests the states for the selected country. When a state changes, it requests only cities belonging to that country and state. The demo keeps the page open throughout: no form reload is needed to fetch options.

This small function is used by both dependent dropdowns. Each new option is created using Option(text, value), so values returned by the server are treated as text rather than executable HTML.

function replaceOptions(select, values, label) {
    select.replaceChildren(new Option(label, ''));
    for (const value of values) {
        select.add(new Option(value, value));
    }
    select.disabled = values.length === 0;
}

Third dropdown list: City

The city list begins disabled. Once the user chooses a state, the browser sends both the country and state values to ajax-dd3ck.php. The server validates the selection and uses parameterized database queries to return matching cities as JSON.

This shortened example illustrates the city request from inside an asynchronous function. The complete demo additionally cancels outdated requests, shows network errors, resets stale selections and prevents an incomplete form from being submitted.

async function loadCities(countrySelect, stateSelect, citySelect) {
    const params = new URLSearchParams({
        country: countrySelect.value,
        state: stateSelect.value
    });
    const response = await fetch('ajax-dd3ck.php?' + params.toString());
    const result = await response.json();
    if (!response.ok || !result.ok) {
        throw new Error(result.error || 'Unable to load cities');
    }
    replaceOptions(citySelect, result.city, 'Select a city');
}

The response contains a state array, a city array and the selected values. For example, selecting IND and then Tamil Nadu produces a city list that includes Madurai and Coimbatore in the supplied sample data.

What the PHP JSON processor does

The endpoint ajax-dd3ck.php accepts a GET request containing a country code and, optionally, a state. It checks the input types and lengths, confirms that the state belongs to the selected country, then uses PDO prepared statements to select distinct states and matching cities. An invalid selection produces a JSON error instead of an HTML fragment or exposed database error.

When a user changes the country, the existing state and city selections are cleared. The final Submit button is enabled only after all three lists have a selection. The separate ajax-dd3-details.php processor validates and HTML-escapes the submitted values before displaying them; this demonstration does not modify the database.

For the database sample, use the SQL dump inside ajax-dd3.zip on a separate local test database. Do not import sample records into production. Compare the reload-based three-dropdown example if you want to understand the difference between traditional page reloads and asynchronous requests.

Download the AJAX dropdown source



Subscribe to our YouTube Channel here



plus2net.com







Sajin

19-06-2014

Hi there,

First of all, I am very thankful for you for giving this drop down list examples. I am new to ajax, so I encountered some problems...

I was using your Three interlinked dropdown listbox using Ajax & PHP.
I found a problem that, when the country name has some space in between then the second drop down won't display any values.

You have given GBR,IND like that , but when I changed the IND to "IND ABC", the the second drop down for that particular country was not shown.

It am struggling with this for the last two days. If you can give me a solution for this then it would be very helpul.

Can it be done without using PDO. Because the config file I have with me is not using PDO. So if it can be done only using PDO then it will be very risky for me.

Please help me with this Please reply.........

Thank you
Sajin
smo

19-06-2014

Add single quote to $row[country] like this '$row[country]'
Wdjoe

29-06-2014

There is a problem with your code and I can not figure out how to correct it.
If there is more than one city name for a state, only the first city name on the list can be chosen.
For example... If you choose "USA" then choose "California" the city name that will be displayed is "Los Angeles", but if you try and change that city name for another city name in California such as "San Jose" it reverts back to "Los Angeles".

Please help, I have been trying to find a solution for hours.
smo

03-07-2014

It is fixed now. Check once. Thanks for pointing this bug.
Jay

14-04-2015

Hey, thanks for your great example! I have a question, how can post additional information with subcat2? For instance Banana Hot description
smo1234

16-04-2015

All dropdown list boxes are part of FORM. So any textbox or textarea can be included to carry extra information.
Jerome

15-06-2015

Hey, thanks for your great tutorial.
I have a question, where is the dependence of the dropdown menu created. How can I chance it?
I would like to have an input field at the beginning, and then the second dropdown menu have to take options (output from a select-command, dependent on input from the input field.

(Sorry for my bad english, I hope it is understandly and correct enough.)
smo

15-06-2015

Inside zip file ( download ) you will get ajax-dd3ck.php file. In that there are SQL command with where clause to manage the output.

You can take the input box data also add into the where condition to get matching output for next dropdown list
Jerome

16-06-2015

Hey, thanks for your help.
Unfortunately, I 'm not so good in web design , and certainly not with AJAX and Javascript. Could you possibly help me in more detail?
I'm in an important project and need help. I need an input , and a click on a button, after that the following drop down menus should be filled with select commands from php. I do not know what I have to change ..
smo1234

16-06-2015

This can be done, pl open one thread in forum, we will post there.
JeromeAtom

17-06-2015

Ok. I put my question in this thread: https://www.plus2net.com/forum/topic.php?topic_id=3636

Tanks for your help.
Rob Ogden

24-07-2015

Great code, thanks. However, I would like to use this with 3 separate database tables, and it only appears to allow for a single column per select, i.e. the option (London, Birmingham) and not an ID. Any easy way of changing the code to allow for the 2 columns to pass through to the city select?
vasanth

21-11-2016

Dear All, thank u for this it is really helpful for me, but i need after the values are selected from drop down list. how to fetch the selected value into the another database using php echo method the sql variable. kindly suggest my query.

18-07-2021

I have used the code for my page. However, I want the select boxes to have some initial slecetd values that are retrieved from a database. How can I do that?




PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer