9lessons programming blog
Loading Search
9lessons Bring Friends
Wall Script
Follow Me:
Friday, August 6, 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
Comments
{ 113 comments }
The Motyar said...

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

Amit said...

nice script.. thanks

Yoosuf said...

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

dskanth said...

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

adnan zulkarnain said...

nice script.. like it!

drakethegreat said...

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

KanZonk said...

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

sivrikaya said...

nice share thank you bro

Anonymous said...

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

Michael said...

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.

Nobita said...

Thanks You.

Y5cafe said...

very useful script
Thank You So Much

Prashant said...

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

Anonymous said...

anyone know how to make this 5 level ????

Anonymous said...

how to make this work on 3 select boxes

Anonymous said...

Cool and simple !!! 10x :)

Anonymous said...

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

Prakash said...

nice one :-)

nguyen hoan said...

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?

hoannguyen said...

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

Yasir Malik said...

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

Anonymous said...

Thanks a lot ! it's very useful :)

Anonymous said...

thnks

Mark said...

Awesome, best I've found in my searches.

Anonymous said...

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

Anonymous said...

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

Anonymous said...

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

ishan said...

can anyone provide this script in jsp pleasse

damara said...

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

Anonymous said...

JSP please

Anonymous said...

it doesn't work with IE8 but it work fine on firefox

Anonymous said...

I can not recover the value of city after sending the form

Why??

Anonymous said...

ur simpliy great

Anonymous said...

Awesome...................

Emilio Cs said...

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?

WebHostingAnda said...

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

Anonymous said...

I want to use a textfield instead of select!

Anonymous said...

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

Anonymous said...

Hi budy,
Great post, thankyou very much

Anonymous said...

Thank you!

Manoranjan Jena said...

Thank you very much..

Anonymous said...

Nice Job! Thank you.

Seth said...

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.

Seth said...

It multiplies the select boxes -.-

miya said...

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

Anonymous said...

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

Anonymous said...

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

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

Anonymous said...

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

TipsGet said...

Thank you for sharing. I need this script.

dataforlie said...

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);

});

aarthy said...

really useful

aarthy said...

Really nice its very useful to me

Duarte said...

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

Rk Mudhiraj said...

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

SHIV - the eternal destroyer said...

Works Fine...Thank you :)

Anonymous said...

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

Anonymous said...

great!:-)

Anonymous said...

great work yar!!!

Anonymous said...

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. :)

Mohan said...

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.

Anonymous said...

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

Anonymous said...

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

Kunal Jog said...

Nice one shree. Its really useful

Shazzad said...

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.

Anonymous said...

This is totally not good normalization,

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

David Lenox said...

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

- This is a brother from the Isles of Solomon.

Anonymous said...

thks men
salutes from CHILE!

Johan said...

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

Santosh Kumar Kar said...

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

Anonymous said...

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

Juanjo said...

Nice, thanks

Mr Butt said...

You are great!!!!!!!!!!!!!!!!1

Anonymous said...

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

Anonymous said...

Thanks a lot, easy & good explained

Anonymous said...

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.

Anonymous said...

great

kmillen said...

Well done!

Raj said...

Great ...Well said..Thanks..

Anonymous said...

well done, so, how make 4 chainbox with mysql db

Anonymous said...

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 ?

Anonymous said...

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).");

Anonymous said...

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!

Jeroen van Hezik said...

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.

Jeroen van Hezik said...

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]

Kevin Ouk said...

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.

venkatesh said...

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

Anonymous said...

Thank a lot

Unknown said...

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.

Anonymous said...

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

Craig Marsala said...

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?

Yogesh Gurjar said...

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

Anonymous said...

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

Anonymous said...

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.

Anonymous said...

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

Prashant Gunjal said...

I like it

jeanSot said...

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

jeanSot said...

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

®@mÐäÑ said...

Thank bro.. really help me! nice script

Kajal Semwal said...

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

Anonymous said...

superb!!!!!!!!!!!!

Anand said...

thanku very much, its very nice.

lập trình web said...

thanks u so much. great article

free wordpress themes said...

good. thanks u very much

Anonymous said...

thanks dude....

Knowledge world said...

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.

Muhammad Taufiq Muslih said...

thank you,, very helpfull..

Anonymous said...

thank you, very simple nice script. well done.

Ouekdi Hamza said...

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?

Noman Ibtian said...

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

Anonymous said...

Thank you so much..

Anonymous said...

Thank you!!! :)

Mostafizur Rahman said...

Thanks!
It works fast............

Guru said...

Thank you

Post a Comment