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:&nbsp;<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:&nbsp;<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

Share this post: