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

[button_round color=”blue” url=”infotuts.com/demo/cascaded-drop-down-jquery-php/”] Live Demo [/button_round]  [button_round color=”blue” url=”infotuts.com/demo/cascaded-drop-down-jquery-php/download.html”] Download [/button_round]

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.


Posted

in

, , ,

by

Tags:

Comments

116 responses to “Cascaded Dropdown with jQuery Ajax and PHP”

  1. poonam Avatar

    very helpful tutorial, thanks for posting.

  2. Jack Avatar
    Jack

    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. Sanjeev Avatar

      Hi Jack,

      Email list has been updated, please get your file now.

      1. Alvaro Avatar
        Alvaro

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

        Thanks

        1. Chris Avatar
          Chris

          >>>
          Sorry, We dont have your email. Please Subscribe Below
          <<<
          Still?

  3. Al Avatar
    Al

    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

    1. Sanjeev Avatar

      Hi Al,

      I have refreshed the email list. Please go ahead and get your file.

      Thanks:
      Sanjeev

      1. Al Avatar
        Al

        Thanks Sanjeev, saved me a lot of headaches!

        1. Nabeel Zafar Avatar
          Nabeel Zafar

          Please refresh it again

  4. James Avatar

    Hi,

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

    James

    1. InfoTuts Avatar
      InfoTuts

      Please get your file now. Email list has been updated.

      1. Andy Avatar
        Andy

        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?

  5. Ashuq Avatar
    Ashuq

    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. InfoTuts Avatar
      InfoTuts

      Please get your file now.

      1. Ashuq Avatar
        Ashuq

        Hi

        I went back to

        https://infotuts.com/demo/cascaded-drop-down-jquery-php/download.html

        entered my email address again but still NOTHING happens .

        I made sure my email address is correct (naturally).

        Any ideas will be appreciated . . Thanx in advance !!

        1. InfoTuts Avatar
          InfoTuts

          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.

          1. Krimoli Avatar
            Krimoli

            i need the code

  6. Maktlos Avatar
    Maktlos

    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. InfoTuts Avatar
      InfoTuts

      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.

  7. fadoo Avatar
    fadoo

    very help post thank you for posting this type of helpful tutorial

  8. bidhi Avatar
    bidhi

    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

  9. msu Avatar
    msu

    i sent to you my email addr. why don’t it download?

    1. InfoTuts Avatar
      InfoTuts

      Please download your file. Email list is updated every 12 hoursa

  10. msu Avatar
    msu

    Thankyou for posting

  11. Ray Burnside Avatar

    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( “” );
    }
    });

    });

  12. Ray Burnside Avatar

    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. P. Karas Avatar

      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

  13. venkat Avatar

    please update mail list

    1. InfoTuts Avatar
      InfoTuts

      Done 🙂

  14. Tshepang Avatar
    Tshepang

    please update mail list

    1. InfoTuts Avatar
      InfoTuts

      Done 🙂

  15. Philippe Avatar
    Philippe

    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.

    1. InfoTuts Avatar
      InfoTuts

      Done, please get the file.

      Thanks:
      Sanjeev

  16. Gabor Por Avatar

    Same issues as others. Subscribed, but couldn’t download the file. Update the list please with me too. Thank you.

  17. Gabor Por Avatar

    Wow. Sanjeev was fast. I already got the reply and the files. Thanks for all and the article too.

  18. Kel Avatar
    Kel

    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.

  19. Kel Avatar
    Kel

    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

  20. Bobi Avatar
    Bobi

    Please update mail list!

  21. Adrian Avatar
    Adrian

    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.

    1. InfoTuts Avatar
      InfoTuts

      Please download the file.

      Thanks:
      InfoTuts

  22. Cyferc Avatar
    Cyferc

    Please update mail list!

    1. InfoTuts Avatar
      InfoTuts

      Done!

  23. Don Wolli Avatar
    Don Wolli

    I am obviously to stupid to register! HowTo?

  24. Jiteen Avatar
    Jiteen

    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!

    1. InfoTuts Avatar
      InfoTuts

      Done,
      Please get your file now 🙂

  25. Don Wolli Avatar
    Don Wolli

    Sorry, We dont have your email. Please Subscribe Below
    I entered my Email in “Subsribe here”

  26. ss Avatar
    ss

    Please update mail list!

    1. InfoTuts Avatar
      InfoTuts

      Done

  27. pratyush Avatar

    thanks for the information , i am trying to make cascade drop down like on this page http://www.rtuexam.net/College/selColl.php .But cascade is not working .
    I will be very thankful if u provide a clone of this page.

  28. Atul Tiwari Avatar
    Atul Tiwari

    Please update email list
    Thanks.

  29. dinesh Avatar
    dinesh

    update mail list!!! please save me from headache!!!thanks in advance

    1. InfoTuts Avatar
      InfoTuts

      Done 🙂

  30. anup Avatar
    anup

    Please update the mail list as I havent received the code yet

  31. kelly Avatar
    kelly

    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!

  32. Himanshu Chadha Avatar
    Himanshu Chadha

    Please update the mailing list. Cannot receive the download link.

  33. Pramod Shah Avatar
    Pramod Shah

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

    Thanks.
    Pramod Shah

  34. Vidhu Avatar

    Please send me the file…

  35. usman Avatar

    Update email please i need to download the file thanks

  36. andrew Avatar

    there is a problem in downlod file i subscribed but there is no data downloded please confirm me i need this code

    1. InfoTuts Avatar
      InfoTuts

      Please download your file now.

  37. kunal Avatar
    kunal

    Hi can you please refresh your email list?
    And thanks for the great tut 🙂

  38. tara khati Avatar
    tara khati

    i cannot download data even After subscribing,what i do please help;

  39. Dillon Avatar

    i cannot download data even After subscribing,what i do please help;

  40. Mazroof Avatar
    Mazroof

    i also cant download the file plz help

    1. InfoTuts Avatar
      InfoTuts

      Email list has been refreshed please download the file.

      Thanks

  41. […] Guys, We are getting good response for our simple tutorial on Cascaded drop down with jQuery, Ajax and PHP. In comments and emails I am usually asked on how to save the value back to database. So In this […]

  42. sam Avatar
    sam

    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

  43. Rajesh Kumar Avatar

    Hello Techguy,

    I have subscribe to feedburner. But I am not able to download it. I need it very urgent.

    Thanks

  44. aman Avatar
    aman

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

  45. aman Avatar
    aman

    please update mail list..

  46. Juan Avatar
    Juan

    Hey there.

    Subscribed but still can’t download the file. It says I’m not subscribed. Please, help.

    1. InfoTuts Avatar
      InfoTuts

      Hi Guys,

      Please download the file. Email list has been updated

  47. yk Avatar
    yk

    update the mail list pls.

  48. Jo Avatar

    i ve succesfully registered but i can login to get the file.

    1. InfoTuts Avatar
      InfoTuts

      Email list has been updated. Please get your file now.

      Thanks:
      Sanjeev

  49. Jasjeet Singh Avatar
    Jasjeet Singh

    Hi Sanjeev

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

  50. Diego Avatar
    Diego

    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 !

    1. InfoTuts Avatar
      InfoTuts

      Done, Please get your file now.

  51. InfoTuts Avatar
    InfoTuts

    Hi,

    You can download the code now.

    Thanks:
    Sanjeev

  52. gridfree Avatar
    gridfree

    can you please update email again? ty

  53. shardana Avatar
    shardana

    can you please update the list?
    thanx!!!!

  54. Dhaval Avatar
    Dhaval

    Can you please update the list now?
    I have subscribed but not able to download code.

    Thank you

  55. shanghai_ed Avatar
    shanghai_ed

    Can you please update the list now? thx

    1. InfoTuts Avatar
      InfoTuts

      Please get your file now.

  56. Rakesh Negi Avatar
    Rakesh Negi

    Please update mail list… 😛

    1. InfoTuts Avatar
      InfoTuts

      Hi,

      Please get your file.

  57. Sai Avatar
    Sai

    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

  58. Rachelle Avatar
    Rachelle

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

    1. InfoTuts Avatar
      InfoTuts

      Hi,

      Please try downloading it now.

  59. Rachelle Avatar
    Rachelle

    This works perfect for dropdowns how would you do the same thing with radio button group

  60. Diego Avatar
    Diego

    Great tutorial! Do you mind refreshing the page? I woudl appreciate it greatly.

    1. InfoTuts Avatar
      InfoTuts

      Hi.

      Please get your file now 🙂

  61. ziad Avatar
    ziad

    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

  62. David Avatar
    David

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

    Thanks,

    David

    1. SGT Avatar
      SGT

      Plz refresh mail list.

      Thanx

  63. eddy Avatar
    eddy

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

    thank you,
    eddy

  64. Jürgen Avatar
    Jürgen

    Could you please refresh the subscription mailing lists.

    Jürgen

  65. coder Avatar
    coder

    thank u so much..

  66. Anbu Avatar

    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. InfoTuts Avatar
      InfoTuts

      Hi,

      You should be able to get the file now.

      Thanks:
      Sanjeev

      1. shweta.mayekar695@gmail.com Avatar

        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

        1. InfoTuts Avatar
          InfoTuts

          Hope you have downloaded the file as email list was refreshed

  67. april Avatar
    april

    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! 🙂

  68. Fred Avatar
    Fred

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

    Thanks,
    Fred

  69. projoktibangla Avatar
    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

  70. J Dorst Avatar
    J Dorst

    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

    1. InfoTuts Avatar
      InfoTuts

      Done !!

  71. wahab Avatar
    wahab

    plz refresh

  72. Rob Avatar
    Rob

    Please refresh email list – demo looks great, but keen to see code.
    Thanks!

  73. Neha Avatar
    Neha

    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 🙂

  74. Neha Avatar
    Neha

    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”]; ?>

  75. naresh Avatar
    naresh

    Great .. i am able to download

  76. shivbabbar786@gmail.com Avatar

    I have subscribed with my email but still download button is not working for me. Please send source code of this tutorial. Thank you.

    1. InfoTuts Avatar
      InfoTuts

      Please download now.

  77. Marie Avatar
    Marie

    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

    1. Marie Avatar
      Marie

      Issus solved