Cascaded Dropdown with jQuery Ajax and PHP

Cascaded drop down lists or dependent dropdown list are easy to create in PHP using jQuery and ajax. It’s a good idea to filter things and show user what is needed to be displayed. Suppose we have to create a form where we want users to select a cricket player with his country. So what we would do is first ask him to select a country and then in second drop down list he will see only those players name that play for that particular selected country. So the idea is to populate players drop down list based on selected country. In this tutorial we would be doing this using PHP and jQuery.

So we will create a simple cascaded drop down with country, state and city as three drop downs.

cascaded

Live Demo   Download

We have created a database with three tables to store information about country, state and city. You will get SQL query to create tables in downloaded file. Now we will focus on how to populate these dropdowns based on value of previously selected dropdown. Below is code from index.php that will populate country dropdown from database:

</p>
<div id="dropdowns">
 <div id="center" class="cascade">
 <?php
 $sql = "SELECT * FROM tbl_country ORDER BY country_name";
 $query = mysqli_query($con, $sql);
 ?>
 <label>Country:
 <select name="country" id = "drop1">
 <option value="">Please Select</option>
 <?php while ($rs = mysqli_fetch_array($query, MYSQLI_ASSOC )) { ?>
 <option value="<?php echo $rs["id"]; ?>"><?php echo $rs["country_name"]; ?></option>
 <?php } ?>
 </select>
 </label>
 </div>
 <div class="cascade" id="state"></div>
 <div id="city" class="cascade"></div>
 </div>
<p style="text-align: justify;">

Now main part comes here, we have to show only those states in second dropdown which belong to the country selected in first dropdown. So we will use jQuery and Ajax to retrieve selected country’s ID and send it to fetch_state.php. Below is our jQuery code: 

</p>
<script>
$(document).ready(function(){
$("select#drop1").change(function(){

var country_id = $("select#drop1 option:selected").attr('value');
// alert(country_id);
 $("#state").html( "" );
 $("#city").html( "" );
 if (country_id.length > 0 ) {

 $.ajax({
 type: "POST",
 url: "fetch_state.php",
 data: "country_id="+country_id,
 cache: false,
 beforeSend: function () {
 $('#state').html('<img src="loader.gif" alt="" width="24" height="24">');
 },
 success: function(html) {
 $("#state").html( html );
 }
 });
 }
});
});
</script>
<p style="text-align: justify;">

Above jQuery code will be used similarly to fetch city’s name based on selected state. So we will put code in fetch_city.php file. You can check that by downloading our source file.

When I was creating this tutorial my friend suggested me that why do you need to enter all the data in database? Its logical because what I have entered in database is static data that is never going to change and is limited. So a better option would be to dump entire data in a JSON file and populate these drop downs from JSON file. I will also post that tutorial soon. Please share this simple and useful tutorial with friends.

116 thoughts on “Cascaded Dropdown with jQuery Ajax and PHP”

  1. Dear Sir and Lady:

    I subscribed InfoTuts and you return me a message informing the verification. But I cannot download the free-code. In response, it popup a line saying I still don’t subscribe. Why?

    Jack

      1. Same problem here my friend. Can you please refresh the email list, please? I am looking forward to check those files!

        Thanks

  2. Hi,

    Same problem as above, I registered last night and I still can’t download, it says it doesn’t have my email address.

    Al

  3. Hi,

    I have tried to register myself in order to download source code but I haven’t succeeded, can you please help?

    James

      1. Same problem as all above, I registered and I still can’t download, it says it doesn’t have my email address.

        Please can you refresh the email list?

  4. I have tried to register myself in order to download source code but I haven’t succeeded, can you please help?

    Hoping it will work just as good as the demo!!

        1. Hi, I think you are using FF. We had some issues with FF browser which is fixed now. Please get your file now. Let me know if any trouble in downloading.

  5. Crazy manual system for Subscription and download – i do not understand how you possible continue this Sh—t.
    Read all comments and you understand that all have same prb and you repeat same repaly “Please get your file now. Email list has been updated”……………………

    1. Hi Maktlos,

      I know its frustrating so for our future download either we will provide real time subscription and download or we will give direct links to downloads.

  6. Suppose Select Country ans State put in database when be edit a same form in php how these state will automatically select this was a great issue

  7. Sanjeev,

    many thanks for the cascading drop down menus code. I have a small problem in as much as I can get it to work fine using mysql with my databases but the second drop down doesn’t register as a POST variable in the form output.

    I only need a single dependent drop down for a regional speech dialect dependent on the country selected. The drop downs populate absolutely fine. If you have any ideas I would be eternally grateful (well for a few weeks anyway :-)).

    My code in the main page is

    Country:

    Please Select

    <option value="”>

    $(document).ready(function(){
    $(“select#drop1”).change(function(){

    var accent_id = $(“select#drop1 option:selected”).attr(‘value’);
    // alert(accent_id);
    $(“#dialect”).html( “” );

    if (accent_id.length > 0 ) {

    $.ajax({
    type: “POST”,
    url: “/full/fetch_state.php”,
    data: “accent_id=”+accent_id,
    cache: false,
    beforeSend: function () {
    $(‘#dialect’).html(”);
    },
    success: function(html) {
    $(“#dialect”).html( html );
    }
    });
    }
    });
    });

    and in fetch_state.php*************************************

    $accentID = trim(mysql_escape_string($_POST[“accent_id”]));

    $sql = “SELECT * FROM dialects WHERE countryID = “.$accentID .” ORDER BY dialect”;
    $count = mysqli_num_rows( mysqli_query($db, $sql) );
    if ($count > 0 ) {
    $query = mysqli_query($db, $sql);
    ?>

    Please Select

    <option value="”>

    $(document).ready(function(){

    $(“select#drop2”).change(function(){

    var dialect_id = $(“select#drop2 option:selected”).attr(‘value’);
    // alert(dialect_id);
    if (dialect_id.length > 0 ) {
    $.ajax({
    type: “POST”,
    url: “fetch_city.php”,
    data: “dialect_id=”+dialect_id,
    cache: false,
    beforeSend: function () {
    $(‘#city’).html(”);
    },
    success: function(html) {
    $(“#city”).html( html );
    }
    });
    } else {
    $(“#city”).html( “” );
    }
    });

    });

  8. Has anyone come across the Cascaded Dropdown with jQuery Ajax and PHP working until you submit the form and then the dependent drop down does not appear in the POST variable.

    Ray

    1. hallo

      did you solve your issue? I need to store selected value (or id of chosen value) from third dropdown menu in variable to use it later. any ideas?

      regards

  9. HI Sanjeev,

    Looks like I’m having the same problem downloading the code as most. Can you please add my name to your mailing list so that I can access downloads. Thx.

  10. Looks like I’m having the same problem downloading the code as most. Can you please add my name to your mailing list so that I can access downloads. Thx.

  11. Sanjeev,
    Thanks for the link. I got a quick question. After you have made your last choice, is there a way to display a button below the dropdowns and pass the value of the id? In my dropdown lists, I may use the 1st, 2nd or 3rd dropdown… So when I get to the final list(choice), I would like a button so I can pass the last selected value.

    Thanks

  12. Hi,

    Same problem as above, I registered last night and I still can’t download, it says it doesn’t have my email address.

    Ad.

  13. Cannnot download the file. Same message “You are not in Subscription List”. Please add me as well so that I can download the file as soon as possible.

    BTW, a very nice example though. thanks a ton. Keep up the good work!

  14. Sanjeev,
    Is there any way to add a submit button below the cascading dropdowns so that I can pass information to another to another form. I would like to pass the last choice made to another page.

    Thanks for the great tutorial!

  15. After subscribing, it is not allowing me to download the source code. How to download the code? Kindly suggest.

    Thanks.
    Pramod Shah

  16. Pingback: Cascaded Dropdown in jQuery Ajax, PHP and MySQL

  17. thanks for the code, however i would like to ask u one thing, after i select a city i would like to perform a search (e.g- get a list of people living in that particular state that is selected from the drop down list)the search would be done from a separate table. i have the code for search but i am not able to merge the two, can u plz suggest me where should i put the code so that i can perform search properly

  18. I have tried to register myself in order to download source code but I haven’t succeeded, can you please help?

  19. Hi Sanjeev

    I subscribed InfoTuts and you return me a message informing the verification. But I cannot download the free-code. Why?

  20. Might you please refresh the email list again ? I am sorry to bother, I have subscribed but the system does not see me yet 🙁

    BTW: Great Solution (I am wondering: anyone has any advice on how ot make the function reusable ? I would like to re-use the same function for several (3) different cascading drop down lists…is there any way to achievethis without rewriting the full code every time ?)

    Thank you so very much for sharing this !

  21. i have a similar scenario like this, i just need two dropdowns first one works fine but the second one is not getting populated. it shows up an error of unidentified index.please help me with this

  22. Hi, Excellent tutorial –
    Could you please refresh your email list so I can download the files for the tutorial
    thank you

  23. I changed the first dropdown to a jquery-ui combobox and now the value is not being passed to the secong dropdown. Could you (anyone) please help me with the issue

  24. Brilliant example!
    Could you please refresh the subscription mailing list please.

    Thanks,

    David

  25. Your work is amazing!!!! Could you please refresh the subscription mailing lists.

    thank you,
    eddy

  26. HI, i appreciate your tutorial .. i would like to try it out.. but i cant download the files…
    though i have subscribed and it has been over 24 hours :/ but still now i cant download the files :/
    Can you refresh your email list or send me a mail (anbustudios3@gmail.com)

    Regards,
    Anbu

      1. Hey.. im eager to have a look at the code. Even after subscribing im unable to download the source code. It keeps displaying the message – “Sorry, We dont have your email. Please Subscribe Below”
        PLEASE do something about this. I have activated the subscription on my email as well

  27. Hi, great solution! I want to try this out but I’m receiving an error that you don’t have my email even though I have already subscribed. If you could refresh mailing list, that would really help.

    Thanks! 🙂

  28. Hi, I am interested in your Cascaded Dropdown code. I recently subscribed but have not heard back.

    Thanks,
    Fred

  29. projoktibangla

    Hi, I appreciate your tutorial. I would like to try it more but can’t download the files.
    Though I have subscribed and it has been over 24 hours :/ but still now I cant download the files :/
    Please, Can you refresh your email list.

    Regards,
    PB

  30. Dear Sanjeev,

    I know this has been asked a million times already… but can I ask you again to refresh the email list?

    Thanks so much,

    Jelle

  31. Am depending on this code to help me proceed with a project. Can you please update the email subscribes asap. Thanks a lot for your help 🙂

  32. I have a minor doubt. Suppose I want to print the entire row instead of a single field value then how can I do that? For example, in the bolded section of the snippet below

    <input type="radio" name="unmapped" value= "” >
    <?php echo $rs[“year”]; ?>

  33. Hi,

    Thanks for this helpfull tutorial.
    In my application the third menu is based on the 2 previous selection instead of the second selection in the tutorial.

    Do you have an idea on how to retreive in the third cascade menu the country id?

    Thnak you for your help.
    Regards

Comments are closed.