AJAX-ified Selects Using Prototype
Recently, I had another project where I needed to use AJAX to fill in a SELECT element based off of values from another SELECT. Previously I had used some very detailed and difficult javascript from an example found in the Apple Developer documentation. I have used this code before so I knew it, but I wanted to get something a bit easier. I was already using the Prototype framework in my code, so I figured I’d use Prototype for this as well.
However, I found no documented way to parse XML using prototype, so with a bit of toying around I was able to find a pretty simple solution.
First of all, here is the html I have for the two selects I need to work with.
[html]
State:
Counties:
[/html]
The first select field has a list of states that when selected, will fill in the second select element with counties from the selected state. I could have gone the easy way and just replaced the counties element with HTML, but I wanted my counties to be returned in XML. As I mentioned, Prototype didn’t have any documented way of easily parsing XML nodes.
To start, the states select calls this function when the selection is changed:
[js]
function searchStates(){
var s = $F(’states’);
var url = ‘ajax_select.php’;
var pars = ’state=’ + s;
var myAjax = new Ajax.Request( url, { method: ‘get’, parameters: pars, onComplete: showResponse });
}
[/js]
This function opens a new AJAX request through Prototype. It passes the value in the state selection box to ajax_select.php in the form of a GET request. On the server side I have the referenced php file to handle the request, and return some XML. (Obviously this file is simplified for example purposes).
[php]
< ?php
header("Content-Type: text/xml");
print'‘;
?>
< ?php if($_GET['state'] == "CO") { ?>
< ?php } ?>
< ?php if($_GET['state'] == "OR") { ?>
< ?php } ?>
[/php]
This file essentially returns an ID number, state, and county for the state passed in the GET request. It opens sending a ContentType of xml so that it doesn’t come back as text, and we add the xml declaration after that. These two statements are required otherwise the javascript gets text instead of XML, and can’t handle it the way we want.
To start out the response handling function, I call it showResponse. In the Prototype ajax request call, I told it onComplete: showResponse, which tells it to call the showResponse function if the request completes.
[js]
function showResponse(originalRequest){
}
[/js]
This is the basic outline of the script. Using the prototype call for an element by its ID, I get the counties element. I need to clear it out, so I loop through it’s options and remove any.
[js]
var c = $(’counties’);
while (c.length > 0) {
c.remove(0);
}
[/js]
Now my target element is clear. But the problem I set out to resolve, is the fact that Prototype doesn’t have any easy way of sorting through the child nodes and returning values. My solution is to pull the nodes out by name, since I know the names of the nodes I need.
[js]
var tagValue = originalRequest.responseXML.getElementsByTagName(’county’);
var tagId = originalRequest.responseXML.getElementsByTagName(’id’);
[/js]
Now all we need to do is iterate through the array returned. I just picked the first array although it really doesn’t matter as both should have the same counts as they originate in the same records. I create a new option for the select element for each one, with a value of the ID I’m pulling from the XML, and text of the county name. IE handles this differently than other browsers, so I need to use try/catch to get past errors. IE uses nodeName.text while everyone else uses nodeName.textContent.
[js]
for (var i = 0; i < tagValue.length; i++) {
var opt = document.createElement("option");
try {
opt.text = tagValue[i].textContent;
opt.value = tagId[i].textContent;
c.add(opt, null);
}
// IE needs special handling
catch(ex){
opt.text = tagValue[i].text;
opt.value = tagId[i].text;
c.add(opt);
}
}
[/js]
That's it! Checkout the working example here!
Or you can Download these source files along with Prototype here.