Ajax Cascading Drop-down Example
December 2, 2005
If you are new to Ajax and would like to learn more,
this article was written for you! Use it as a starting
point to learn the basics of sending requests,
receiving xml responses and using DHTML to update inputs
on an HTML page. It's actually pretty easy, we'll show you how.
This example contains only 4 files and will work on
web servers that support asp or php. A recent version
of either IE or Firefox is required to run the client-side
HTML and Ajax JavaScript.
Cascading Drop-down List
A common requirement in many web applications is for the selection of one drop-down list to change the content of another list on the same page. Using Ajax, we can re-populate the dependent drop-down list without having to submit the entire page. A simple request is made to a data provider web page and the data we need for the second list is returned as xml.
To try the example click here.
Running the Example Code
To run the example code, download the file ajaxexample.zip and extract to a directory on your development machine. Create a virtual directory that points to the directory containing the extracted files. If your machine supports PHP but not ASP then you will have to modify the AjaxCode.js file in the js directory.
uncomment this line in AjaxCode.js:
requestUrl = "xml_data_provider.php" + "?filter=" + encodeURIComponent(selectedContinent);
Next, point your browser to the index.html in your new virtual directory. It may look something like this: http://localhost/ajaxexample/index.html
How it Works
When a user selects a value in the first drop-down list the onChange event calls a function in AjaxCode.js named
ContinentListOnChange(). In this function a
request for xml data is made to the xml_data_provider.asp (or .php)
page. A querystring parameter with the selected continent value
is passed to this page and an xml string of country names is
created. The response xml is sent back to an XMLHTTPRequest object
within AjaxCode.js. The reponse does not go directly to
the dependent drop-downlist. A function named
StateChangeHandler() in
AjaxCode.js is notified when the xml data has been returned to the
client and a call is made to PopulateCountryList() which extracts
values from the xml and uses DHTML to populate the country drop-down
list.
To learn more, open Index.html, AjaxCode.js and xml_data_provider.asp (or .php) in your favorite text editor. All files are fully commented.
What's Next
If you plan on building sites with Ajax, a solid understanding of manipulating xml in JavaScript is essential. Try this xml/js tutorial at codetoad.com.
A more advanced Ajax tutorial can be found here on the SkillFusion DevZone site.
We hope you found this article helpful - thanks for visiting.

