Hey Geeks, Many of you have already gone through a simple javascript example script, which lets you swap elements from two select boxes. I posted this blog post few months back.
In this post I am going to show you, how you can use ajax to populate a dropdown, on the basis of value selected in some other dropdown. As the web is growing bigger and every site adds much better functionality to its forms. This sort of ajax populated dropdowns are pretty common and are handy to use. You can see the demo of this example below, choose a state it will populate the corresponding list of cities in the city dropdown.
Excited to see the code ? So let us now move to the code which is powering the above demoed ajax dropdowns. This script has three parts, HTML, Javascript (embeded Ajax functionality), PHP (serverside script to return the fresh data).
Note: For this example I am using a simple array in PHP script to return list of cities, but while implementing the script you can change the data source to database or something. All you have to make sure is that you return something to which can be handled by Javascript function.
Here is the HTML and Javascript code.
<html>
<head>
<title>Demo of City/State via Ajax</title>
<script type="text/javascript">
//define the absolute path to your php script here
var site_root='';
//function to create ajax object
function pullAjax(){
var a;
try{
a=new XMLHttpRequest()
}
catch(b)
{
try
{
a=new ActiveXObject("Msxml2.XMLHTTP")
}catch(b)
{
try
{
a=new ActiveXObject("Microsoft.XMLHTTP")
}
catch(b)
{
alert("Your browser broke!");return false
}
}
}
return a;
}
//this function does the ajax call, and appends cities into the second dropdown
function populate_cities(x)
{
obj=pullAjax();
var cities_list=document.getElementById('city');
obj.onreadystatechange=function()
{
if(obj.readyState==4)
{
//returns comma separated list of cities after successful ajax request
var tmp=obj.responseText;
//split function returns array of city
cities=tmp.split(',');
//if second dropdown already has some data, CLEAR it
if(cities_list.length>1)
clean_cities(cities_list);
//for loop to append the cities
var i=0;
for(i=0;i<cities.length;i++)
append_city(cities[i]);
}
};
obj.open("GET",site_root+"cities_data.php?state="+x.value,true);
obj.send(null);
}
//this gets call in the for loop and creates the options for the dropdown
function append_city(city_value)
{
var cities_list=document.getElementById('city');
cities_list.options[cities_list.options.length]=new Option(city_value,city_value,false,false);
}
//CLEARs the dropdown
function clean_cities()
{
var cities_list=document.getElementById('city');
cities_list.options.length=1;
}
//autoloads the city list, when the page first loads
function autoload()
{
populate_cities(document.getElementById('state'));
}
</script>
</head>
<body onload="autoload();">
<p>Choose a State: <select id="state" onchange="populate_cities(this);">
<option value="California">California</option>
<option value="Alaska">Alaska</option>
<option value="New York">New York</option>
<option value="New Jersey">New Jersey</option>
</select></p>
Choose a City: <select id="city">
<option>Choose City...</option>
</select>
</body>
</html>
Here is the PHP code snippet. Data source for this PHP script is an array, but it can be changed (as mentioned above) depending upon the need.
<?php $state=trim($_GET['state']); //if state is end empty, return blank if($state=='') return ''; $data=array( 'California' => array('San Francisco','South Gate ','South El Monte','Santa Clara','Roseville','Albany'), 'Alaska' => array('Eagle','Deering','Nome','Russian Mission','St. Paul','Whittier','Valdez','Sand Point'), 'New York' => array('Albany','Buffalo','Troy','Geneva','Beacon','Johnstown','Hudson','Cortland','Lockport','New York City'), 'New Jersey' => array('Jersey City','Newark','Elizabeth','Old Bridge','Howell','Atlantic City','Ewing','Fort Lee','Burlington'), ); //return comma seperated list of cities echo implode(',',$data[$state]); ?>
Now let me delve you into its concept and help you to understand how this whole script works.
When you select a state from the first dropdown, an event “onchange” is fired and the function populate_cities is called. This function is responsible of creating request object (using function pullAjax() ) which makes the Ajax call possible.
Ajax call sends the state name as GET parameter to PHP file cities_data.php . The state parameter is sent via javascript which is selected from our first dropdown.
The above Ajax file returns a comma separated list of cities corresponding to the state received as the parameter. In an ideal scenario you might want to query database using state field as the parameter in where clause of your selct query. A generic query which be something like:
Select * from countries where state=’$state’;
This comma separated list of cities is received as response by the same Javascript function. In Javascript function we are using split() function to convert CSV into an array. This array is then iterated and with and append_city function creates options for the second dropdown which seems to be populated then.
We have two supporting functions as well in the script called clean_cities() and autoload(). clean_cities() function is used to clear the cities dropdown, because when the new cities are being populated, the old cities must not be present there as they are from different state. autoload() function is another utility function which populates the cities in the second dropdown by sending an Ajax request, as soon the page finishes loading. That is why autoload() gets called on the onload event.
The code is self-explanatory, you can get the guidance from the inline comments given within the code. If you still face problems running this example, leave a comment, will try to reply you back.
This is a basic example to show you how you can make things smoother and more interactive using Ajax in your coding practice. You can add few more validations using PHP and Javascript to make this script robust and fail proof.
Hope it saves your day !
Stay Digified !!
Sachin Khosla





thanks for this code…
My Pleasure
Good work…
Thanks
Thank you very much for the lesson and code Sachin.
I have copied and pasted the HTML and Javascript code into an html text widget and that worked fine, however, I am not sure where I am to place the PHP code snippet.
If you could please have a look at my blog and let me know what I am doing wrong, I would really appreciate it.
Thanks again.
TDC
Hi,
You can keep the php file in the same level as your html file, it should work then.
thanks its works……
Hi Sachin!
I just want to ask if it’s possible to place 2 of these codes in the same page. I’m building an online store and I want to put 2 sets of these, one for billing information and the other for shipping information. I tried putting the same code twice but only one of them works. Should there be more code for both of them to work? Thanks in advance!
Hi d teo,
Yes you can use the same code for 2 or more drop downs. All you have to do is keep different name and ids of the select boxes and corresponding names in the PHP + JS script.
Hope that helps !
Thanks
Sachin Khosla
I suppose I’m a little confused. How can I easily give each city a unique option value so on select they actually link somewhere. Sorry for such a simple question. Sorry to make you dumb it down.
Got them working ok but just noticed they are not working in IE. Nothing really seems to I guess. Is there something I should do to make these cross browser capable? Thanks for the great article btw.
I am so sorry to having forget that we still live with brainless browsers like IE. In the above example I have missed is the value attribute in the option tag.
Correcting the code, should reflect in few mins. If you don’t see clear the cache.
Hope that works !
THANK YOU!! I found a few other examples first and could not get what I needed (they were all using country as well).
This worked like a charm!
Excellent in the way it is being explained.
Hey its really very helping.i am the beginner for ajax but after reading this i feel very confident about ajax.