Ajax powered city state Dropdown
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.
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.
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’;
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.
Hope it saves your day !
Stay Digified !!