9lessons programming blog
Loading Search
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
Sponsored Links

Share this post

Comments
{ 59 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

Santosh kumar said...

nice

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

Post a Comment

Subscribe now!Recent Posts

Categories

Subscribe now!Popular Posts

People Says

@9lessons thank you for the great tutorials, we truly appreciate your contributions to the design community.

Smashing Magazine

Like Me

follow me
products

9lessons labs

9lessons clouds

Android application

Chrome Extension