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.
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)
)
(
'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/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
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>';
}
}
?>
Its again a very useful script shree, we often need these type of scripts. Thanx for sharing
ReplyDeletenice script.. thanks
ReplyDeleteit has a bug, when i choose country, it shows the the countries in the City combo
ReplyDeleteNice script.... but i feel that this can also be done without jquery, using onchange event for country select box and calling ajax.....
ReplyDeletenice script.. like it!
ReplyDeleteIf you can't code this up yourself in 10 minutes, it's time to get a new job that doesn't involve programming.
ReplyDeleteVery nice post...
ReplyDeletehow to convert this to codeigniter...
nice share thank you bro
ReplyDeleteWhat 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
ReplyDeleteQuite 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.
ReplyDeleteThanks You.
ReplyDeletevery useful script
ReplyDeleteThank You So Much
Nice script...
ReplyDeleteThank You So Much ...\m/\m/
anyone know how to make this 5 level ????
ReplyDeletehow to make this work on 3 select boxes
ReplyDeleteCool and simple !!! 10x :)
ReplyDeleteHi, Nice Worked But How To add chainde for city ( 3 levels ) State ?
ReplyDeleteIndia = Delhi
Delhi = ...etc (state)
Thanks For Reply
Best Regards
nice one :-)
ReplyDeleteI have specific value for 'pid' and 'did' in the database.
ReplyDeleteFor 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?
How can I call this function with body onload for specific value of 'pid' and 'did'?
ReplyDeletehello, i have one suggestion plz do the LIVE DEMO's Link BLANK
ReplyDeleteThanks a lot ! it's very useful :)
ReplyDeletethnks
ReplyDeleteAwesome, best I've found in my searches.
ReplyDeleteFantastic. Exactly what I needed to learn. Thank you.
ReplyDeleteawesome..ur site make my job easy..thanks dude..
ReplyDeletevery nice but i want Dynamic Dependent Select Box using Jquery and Ajax with jsp
ReplyDeletecan anyone provide this script in jsp pleasse
ReplyDeletethank you so much
ReplyDeletei was working on it for many day at last i got it thank you
JSP please
ReplyDeleteit doesn't work with IE8 but it work fine on firefox
ReplyDeleteI can not recover the value of city after sending the form
ReplyDeleteWhy??
ur simpliy great
ReplyDeleteAwesome...................
ReplyDeleteThanks a lot ! it's very useful :)
ReplyDeleteAfter 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?
Wow., it's very useful!! Thanks bro..
ReplyDeleteI want to use a textfield instead of select!
ReplyDeleteJust Rockin Post buddy.... keeeeep the same way in future
ReplyDeleteHi budy,
ReplyDeleteGreat post, thankyou very much
Thank you!
ReplyDeleteThank you very much..
ReplyDeleteNice Job! Thank you.
ReplyDeleteSo 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.
ReplyDeleteAnyways 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.
It multiplies the select boxes -.-
ReplyDeletehey 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
ReplyDeleteThanks mate, Very useful. Converted it to ASP/Access and 3 levels. Thanks.
ReplyDeletevar id=$(this).val();
ReplyDeletevar dataString = 'id='+ id;
i dont get this part which id point that id of database ?
nice tutorial ..
ReplyDeleteregarding 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
Thank you for sharing. I need this script.
ReplyDeletewhat about the load() function. isnt it esier to use it?
ReplyDelete$(".country").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$(".city").load('ajax_city.php?id='+id);
});
really useful
ReplyDeleteReally nice its very useful to me
ReplyDeleteReally nice script.
ReplyDeleteI 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
......SMALL MISTAKE IN SCRIPT.....
ReplyDeletewhen 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.
Works Fine...Thank you :)
ReplyDeleteIT's Works ..Thank's Mr. Srinivas Tamada..awesome code
ReplyDeletegreat!:-)
ReplyDeletegreat work yar!!!
ReplyDeleteThanks... 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.
ReplyDeleteThanks for your help. :)
Hi All,
ReplyDeletei 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.
How do I add a submit button and direct the selected City for example to a separate City page?
ReplyDeleteDear all
ReplyDeleteif 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
Nice one shree. Its really useful
ReplyDeleteThis is just madness, Brilliant work man !!!
ReplyDeleteAnd 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.
This is totally not good normalization,
ReplyDeleteWe can make it in single Data instead of 2..with proper data modelling and normalization
Good work. Could someone please post a solution to view 3 columns.
ReplyDelete- This is a brother from the Isles of Solomon.
thks men
ReplyDeletesalutes from CHILE!
Nice, only one bug!
ReplyDeleteIf you choose a country, and then go back to choosing "--select country--" then the country is showing in the second form
So helpful.
ReplyDeleteThis 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
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...
ReplyDeleteNice, thanks
ReplyDeleteYou are great!!!!!!!!!!!!!!!!1
ReplyDeleteFriends, a doubt.
ReplyDeleteFriends 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
Thanks a lot, easy & good explained
ReplyDeleteI 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.
ReplyDeleteWell done!
ReplyDeleteGreat ...Well said..Thanks..
ReplyDeletewell done, so, how make 4 chainbox with mysql db
ReplyDeleteNice 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 ?
ReplyDeleteLOL.
ReplyDeleteYou 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).");
Can anyone help me modify the code so it works for like 10 forms on one page.
ReplyDeleteI 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!
A very nice script! But how to deal with a selectbox with a multiple="multiple" tag?
ReplyDeleteI 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.
Sorry, already found out! The (multiple) selected values are comma seperated.
ReplyDeleteAnother 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]
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.
ReplyDeletehow to three dropdown list like category->products->brand , how to get the value the dynamic and store the db , can u help me..
ReplyDeletethanks in advance..
Thank a lot
ReplyDeleteHi,
ReplyDeleteI 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.
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
ReplyDeleteGreat 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?
ReplyDeletehi 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
ReplyDeleteit's working ,but when a i use words with qccent it doesn't work ,a traid utf8 encode ,what should i do pls help
ReplyDeletetype: "POST",
ReplyDeleteurl: "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.
I need this but with 3 select boxes, can you help me?
ReplyDeletethank you very much, helped me a lot, finally found what he was looking
ReplyDeletethank you very much, helped me a lot, finally found what he was looking
ReplyDeleteThank bro.. really help me! nice script
ReplyDeleteIts 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
ReplyDeletesuperb!!!!!!!!!!!!
ReplyDeletethanku very much, its very nice.
ReplyDeletethanks u so much. great article
ReplyDeletegood. thanks u very much
ReplyDeletethanks dude....
ReplyDeleteIf 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.
ReplyDeletethank you,, very helpfull..
ReplyDeletethank you, very simple nice script. well done.
ReplyDeleteI have a simple question, I have 2 options which i whant to be putted in the second dropdownbox, how to make them always shown?
ReplyDeleteWhen i run the code,
ReplyDeletebrowser shows
Notice: Undefined index: id in D:\xampp\htdocs\linking\ajax_city.php on line 4
help me, please
Thank you so much..
ReplyDeleteThank you!!! :)
ReplyDeleteThanks!
ReplyDeleteIt works fast............
Thank you
ReplyDeleteit 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 !
ReplyDeletevery nice
ReplyDeleteit 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.
ReplyDeletein 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...
how to store this value in one onother table ??
ReplyDeleteThank you, helped me a lot.
ReplyDeletehow about for 3 drop downs? HELP :(
ReplyDeletethank u! thank u! and thank u! you saved me! i wrote my first ajax with you real helpful post...
ReplyDeletebest code...really helped...
ReplyDeleteThanks.. :)
ReplyDeleteNice code ever
ReplyDeleteThnx
ReplyDeleteGd code
i am clicking on first dropdown it showing content from database but not showing of second dropdown from database.
ReplyDeletehow i solve this problem
i want code for country state and city drop down using ajax
ReplyDeletehow to create 3 dynamic select box with 3 different tables?
ReplyDeletehello sir ,
ReplyDeletethanking very much.
it's a nice script
its work ...but when we edit any post where we use both country and city ..
ReplyDeleteusing 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
HI,,WHEN I CLICK ON DEMO FOR YOUR nice script
ReplyDeletethere 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..
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",
ReplyDeleteThank you .
ReplyDeletehow Data show in input text field?
ReplyDeletenice but i want to write update code for this select boxes how can i know can u please post it
ReplyDelete