Dynamic Dependent Select Box using Jquery and Ajax
Wall Script
Wall Script
Friday, August 06, 2010

Dynamic Dependent Select Box using Jquery and Ajax

How to do dynamic dependent select box using Jquery, Ajax, PHP and Mysql. Dependent select box when a selection is made in a "Parent" box it allow to refresh a "child" box list data. In this post I had given a database relationship example betweent "catergory" and "subcategory". It's very simple jquery code hope you like this.
Dynamic Dependent select box

Download Script     Live Demo

Database
Sample database tables. Data table contains list boxes complete data, data_parent table foreign key relationship with Data table contains parent and child relation.
CREATE TABLE 'data'
(
'id' int primary key auto_increment,
'data' varchar(50),
'weight' int(2),
);

CREATE TABLE `data_parent`
(
`pid` int(11) primary key auto_increment,
`did` int(11) unique,
`parent` int(11),
Foreign key(did) references data(id)
)

Data storing like this.
data data_parent


sections_demo.php
Contains javascipt and PHP code. $(".country").change(function(){}- country is the class name of select box. Using $(this).val() calling select box value. PHP code displaying results from data table where weight='1'
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".country").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;

$.ajax
({
type: "POST",
url: "ajax_city.php",
data: dataString,
cache: false,
success: function(html)
{
$(".city").html(html);
}
});

});

});
</script>
//HTML Code
Country :
<select name="country" class="country">
<option selected="selected">--Select Country--</option>
<?php
include('db.php');
$sql=mysql_query("select id,data from data where weight='1'");
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$data=$row['data'];
echo '<option value="'.$id.'">'.$data.'</option>';
} ?>
</select> <br/><br/>

City :
<select name="city" class="city">
<option selected="selected">--Select City--</option>
</select>

ajax_city.php
Contains PHP code. Displaying results from data and date_parent tables
<?php
include('db.php');
if($_POST['id'])
{
$id=$_POST['id'];
$sql=mysql_query("select b.id,b.data from data_parent a,data b where b.id=a.did and parent='$id'");
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$data=$row['data'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
?>
AJAX and PHP: Building Modern Web Applications 2nd Edition
web notification

132 comments:

  1. Its again a very useful script shree, we often need these type of scripts. Thanx for sharing

    ReplyDelete
  2. it has a bug, when i choose country, it shows the the countries in the City combo

    ReplyDelete
  3. Nice script.... but i feel that this can also be done without jquery, using onchange event for country select box and calling ajax.....

    ReplyDelete
  4. If you can't code this up yourself in 10 minutes, it's time to get a new job that doesn't involve programming.

    ReplyDelete
  5. Very nice post...
    how to convert this to codeigniter...

    ReplyDelete
  6. What is the point of the pid field? it isn't used and always matches the did. Seems you could have just left it out. It is just confusing

    ReplyDelete
  7. Quite bad practice, you should really have 2 tables, a cities table with a country_id field and a countries table and use JOIN's to get the correct data.

    ReplyDelete
  8. very useful script
    Thank You So Much

    ReplyDelete
  9. Nice script...
    Thank You So Much ...\m/\m/

    ReplyDelete
  10. anyone know how to make this 5 level ????

    ReplyDelete
  11. how to make this work on 3 select boxes

    ReplyDelete
  12. Cool and simple !!! 10x :)

    ReplyDelete
  13. Hi, Nice Worked But How To add chainde for city ( 3 levels ) State ?
    India = Delhi
    Delhi = ...etc (state)
    Thanks For Reply
    Best Regards

    ReplyDelete
  14. I have specific value for 'pid' and 'did' in the database.

    For example, the edit product page.

    How can I make it auto select the specific 'pid' and 'did' that load from the database when the page is newly loaded?

    ReplyDelete
  15. How can I call this function with body onload for specific value of 'pid' and 'did'?

    ReplyDelete
  16. hello, i have one suggestion plz do the LIVE DEMO's Link BLANK

    ReplyDelete
  17. Thanks a lot ! it's very useful :)

    ReplyDelete
  18. Awesome, best I've found in my searches.

    ReplyDelete
  19. Fantastic. Exactly what I needed to learn. Thank you.

    ReplyDelete
  20. awesome..ur site make my job easy..thanks dude..

    ReplyDelete
  21. very nice but i want Dynamic Dependent Select Box using Jquery and Ajax with jsp

    ReplyDelete
  22. can anyone provide this script in jsp pleasse

    ReplyDelete
  23. thank you so much
    i was working on it for many day at last i got it thank you

    ReplyDelete
  24. it doesn't work with IE8 but it work fine on firefox

    ReplyDelete
  25. I can not recover the value of city after sending the form

    Why??

    ReplyDelete
  26. ur simpliy great

    ReplyDelete
  27. Awesome...................

    ReplyDelete
  28. Thanks a lot ! it's very useful :)

    After sending the form, I can recover and select the country value, but not the city. How can I load the city options and then select it the submitted value after sending the form?

    ReplyDelete
  29. Wow., it's very useful!! Thanks bro..

    ReplyDelete
  30. I want to use a textfield instead of select!

    ReplyDelete
  31. Just Rockin Post buddy.... keeeeep the same way in future

    ReplyDelete
  32. Hi budy,
    Great post, thankyou very much

    ReplyDelete
  33. Nice Job! Thank you.

    ReplyDelete
  34. So I am trying to incorporate this into WordPress using categories as dropdown menus. I have the original menu being generated through the Wordpress function "wp_dropdown_categories" with a few variables (such as class, depth, etc) to make it only display the highest most categories.
    Anyways it's not working. I have it call ajaxcats.php which checks for an id, then it renders the "wp_dropdown_categories" with the "child_of" category being the value that was passed. Sorry if it is difficult to understand. I can send you the code if you want.

    ReplyDelete
  35. It multiplies the select boxes -.-

    ReplyDelete
  36. hey all i just wanted to know how to have 3 select box and when first select box is selected table view should be there as we select the second box the table view should filter it and so on in the last select box is there any code that does it.(lang:php ajax)plz help im just looking for it

    ReplyDelete
  37. Thanks mate, Very useful. Converted it to ASP/Access and 3 levels. Thanks.

    ReplyDelete
  38. var id=$(this).val();
    var dataString = 'id='+ id;

    i dont get this part which id point that id of database ?

    ReplyDelete
  39. nice tutorial ..

    regarding the Id part to remove confusion

    var dataString = 'id='+ id;

    'id=' is the name of "post" variable to the ajax.php page
    and
    + id ----- here id denotes value of selected country from parent Combo box


    dnd906@gmail

    ReplyDelete
  40. Thank you for sharing. I need this script.

    ReplyDelete
  41. what about the load() function. isnt it esier to use it?

    $(".country").change(function()
    {
    var id=$(this).val();
    var dataString = 'id='+ id;

    $(".city").load('ajax_city.php?id='+id);

    });

    ReplyDelete
  42. Really nice its very useful to me

    ReplyDelete
  43. Really nice script.

    I just have a problem. I'm using a form with styles, and when the select is replaced by ajax by a new select, it loses all the styles. Do you know how to apply again the styles to this select?

    Thanks in advance

    ReplyDelete
  44. ......SMALL MISTAKE IN SCRIPT.....
    when we choose one country in select box then appeared related cities , ok fine.. but again if we choose 'select-country' item in first select box then all country list display in second select box .it is voilated. Please verify once and reply it.

    ReplyDelete
  45. IT's Works ..Thank's Mr. Srinivas Tamada..awesome code

    ReplyDelete
  46. Thanks... really helpful.. that's what i need to do now. I can insert the record into the database. But i have a problem.. how to edit the record (dependent list box)? please show me some example. Very urgent.

    Thanks for your help. :)

    ReplyDelete
  47. Hi All,
    i downloaded the code and it was very useful but is it possible to provide another selection box in which we can provide cities also, currently it is country and states. So can one help me out.

    ReplyDelete
  48. How do I add a submit button and direct the selected City for example to a separate City page?

    ReplyDelete
  49. Dear all
    if you check file ajax_city.php
    we have a sql query as below.
    $sql=mysql_query("select b.id,b.data from data_parent a,data b where b.id=a.did and parent='$id'");

    why there is "b" & "a" is used and what is the purpose of it? it is not defined any where?
    plz help
    thanks to all

    ReplyDelete
  50. Nice one shree. Its really useful

    ReplyDelete
  51. This is just madness, Brilliant work man !!!

    And towards those commenter who said that the same thing could be done in another way, "This is just a directive tutorial which Tamada has posted to let Programmers have a concept without wasting their time by creating a new one to do the similar thing. If you can't inspire, then just stopby. You will probably find free blogs to share your own Talent!!!".

    I usually read 9lessons, and i don't like people post such kind of worse reply without understanding the aim of the author.

    ReplyDelete
  52. This is totally not good normalization,

    We can make it in single Data instead of 2..with proper data modelling and normalization

    ReplyDelete
  53. Good work. Could someone please post a solution to view 3 columns.

    - This is a brother from the Isles of Solomon.

    ReplyDelete
  54. thks men
    salutes from CHILE!

    ReplyDelete
  55. Nice, only one bug!
    If you choose a country, and then go back to choosing "--select country--" then the country is showing in the second form

    ReplyDelete
  56. So helpful.
    This is the one which I was looking for since a week.

    Could you please help me by implementing exact the same using JSon?

    Thanks,
    Santosh

    ReplyDelete
  57. this is a very good post . no doubt at all.... bt how can we do it code igniter..it is not taking any effect with dependency...

    ReplyDelete
  58. Friends, a doubt.

    Friends the script is perfect. however when I duplicate the campousando jquery, the fields do not carry duplicate data is wrong?

    Can anyone help me? I await contact

    Atte.
    Damian / Natal-RN/Brasil

    ReplyDelete
  59. Thanks a lot, easy & good explained

    ReplyDelete
  60. I am new to php, mysql, javascript, ajax.. I had been trying to auto populate dropdown boxes for a week.. Your tutorial was very clear and I was able to accomplish my goal. I really appreciate your presentation of the tasks.

    ReplyDelete
  61. Great ...Well said..Thanks..

    ReplyDelete
  62. well done, so, how make 4 chainbox with mysql db

    ReplyDelete
  63. Nice and simple script that did the job. And how can I set selected attribute if both select box have data read from database. Such as retrieve record for editing ?

    ReplyDelete
  64. LOL.
    You have SQL injection here:
    $sql=mysql_query("select b.id,b.data from data_parent a,data b where b.id=a.did and parent='$id'");

    Dont't use that.
    USE:
    $sql=mysql_query("select b.id,b.data from data_parent a,data b where b.id=a.did and parent=".mysql_real_escape_string($id).");

    ReplyDelete
  65. Can anyone help me modify the code so it works for like 10 forms on one page.

    I have a form with like 20 products and they have to be placed in main and subcategorie.

    I could use the script printing only one product and let someone put it in main and sub categorie, but as the script got like 2000 products I would like to have the option to present like 10 or 20 forms in wich products can be adjusted for price, name, main and sub categorie.

    But now the javascript in the head section needs to be adjusted so it accepts those diverent names in stead of only accepting country and city.
    It now needs to accept like: country001 / city001 and country002 / city002

    Hope I explain properly so you know what I mean and you can help me out here.

    Thanks

    Great script tho!

    ReplyDelete
  66. A very nice script! But how to deal with a selectbox with a multiple="multiple" tag?

    I know how to loop through a conventional $_POST['country'] array with different parents, but i don't know how to deal with an array in AJAX.
    Please let me know.

    ReplyDelete
  67. Sorry, already found out! The (multiple) selected values are comma seperated.

    Another problem: When using a .htaccess file with Rewrite-rules, the complete HTML is written by the Ajax function into the selectbox! How to solve this?

    This is my .htaccess file:

    Options +FollowSymLinks
    AddDefaultCharset utf-8
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.+)(/)?$ index.php?req=$1 [L]

    ReplyDelete
  68. it works fine for me! anyone has the idea of how to disable the second combo box and enable it again after the first box is selected.

    ReplyDelete
  69. how to three dropdown list like category->products->brand , how to get the value the dynamic and store the db , can u help me..

    thanks in advance..

    ReplyDelete
  70. Hi,

    I have created the dropdown with the categories and subcategories, like in the example. But, how can I show the results in the content area of my site?

    Thanks.

    ReplyDelete
  71. Hi i'm trying to add third select that will be load from another table but I did'nt figure out how to do it

    ReplyDelete
  72. Great script... But what happens when you need the VALUE of the select statement to return what the actual selection reads instead of the ID number, a VARCHAR? Any way to get the VALUE to be the same as the SELECTION?

    ReplyDelete
  73. hi iam trying to alphabet sequence searching box than i did not search this box and i am search correct send email code in php language please help me

    ReplyDelete
  74. it's working ,but when a i use words with qccent it doesn't work ,a traid utf8 encode ,what should i do pls help

    ReplyDelete
  75. type: "POST",
    url: "ajax_city.php",
    data: dataString,
    cache: false,
    success: function(html)
    {
    $(".city").html(html);
    }

    if i want to post two values to the file ajax_city.php then what to do? here only dataString is being posted. Please help.

    ReplyDelete
  76. I need this but with 3 select boxes, can you help me?

    ReplyDelete
  77. thank you very much, helped me a lot, finally found what he was looking

    ReplyDelete
  78. thank you very much, helped me a lot, finally found what he was looking

    ReplyDelete
  79. Thank bro.. really help me! nice script

    ReplyDelete
  80. Its working for me.The same code i want to apply with my sign up form where I have city, locality as dropdown,name,mob as text box.Then my city dropdown don't preserve its value..plz help me to find solution

    ReplyDelete
  81. superb!!!!!!!!!!!!

    ReplyDelete
  82. thanku very much, its very nice.

    ReplyDelete
  83. If i want to save the Country and City name based on selection to another table what would be the code. Currently it is saving the ID no.

    ReplyDelete
  84. thank you, very simple nice script. well done.

    ReplyDelete
  85. I have a simple question, I have 2 options which i whant to be putted in the second dropdownbox, how to make them always shown?

    ReplyDelete
  86. When i run the code,
    browser shows
    Notice: Undefined index: id in D:\xampp\htdocs\linking\ajax_city.php on line 4
    help me, please

    ReplyDelete
  87. Thank you so much..

    ReplyDelete
  88. Thank you!!! :)

    ReplyDelete
  89. it works like charm for two select but it is not working with 3 select and another problem here is if someone select the fist one select like in select country if someone change back to select country the next select disappears please reply asap thanks in advance !

    ReplyDelete
  90. it works fine but in my opinion this task can be accomplished with one single table, data table to which we add a city column (which contains 0 for countries and the corresponding id of the country for each city ex. Delhi - 1, Los Angeles - 2 and so on) and we create a self joined relation in sql query.
    in ajax_city.php the sql statement will look like this

    $sql=mysql_query("SELECT data1.id,data1.data FROM test.data data1 INNER JOIN test.data data2 ON data2.id=data1.city AND data1.city = '$id'");

    Of couse this can be extended to the third child and so on...

    ReplyDelete
  91. how to store this value in one onother table ??

    ReplyDelete
  92. how about for 3 drop downs? HELP :(

    ReplyDelete
  93. thank u! thank u! and thank u! you saved me! i wrote my first ajax with you real helpful post...

    ReplyDelete
  94. best code...really helped...

    ReplyDelete
  95. i am clicking on first dropdown it showing content from database but not showing of second dropdown from database.
    how i solve this problem

    ReplyDelete
  96. i want code for country state and city drop down using ajax

    ReplyDelete
  97. how to create 3 dynamic select box with 3 different tables?

    ReplyDelete
  98. hello sir ,
    thanking very much.
    it's a nice script

    ReplyDelete
  99. its work ...but when we edit any post where we use both country and city ..
    using json data implode in php we get city id through database.
    we show in text box .. but its not working in dropdown onchange country. 'city' were not show so how to resolve it. on onclick edit function

    ReplyDelete
  100. HI,,WHEN I CLICK ON DEMO FOR YOUR nice script
    there is some problem arries...
    when i select india as country then all city related to india show in the city dropdown ,,,as when i choose uk or usa then their city is properly show in city dropdown...this is good,,,But problem is in this time when city drop down shows all city related to UK country .....if i change the dropdown value for uk and chose the option select country then city dropdown value changes..And it shows All country list in the city Dropdown main..

    ReplyDelete
  101. the selected value of city is not available. whats the issue. how to use the code in single php file, what change is required at url: "ajax_city.php",

    ReplyDelete
  102. nice but i want to write update code for this select boxes how can i know can u please post it

    ReplyDelete

mailxengine Youtueb channel
Make in India
X