Dynamically Populating a Select Box Using AJAX

Demo and Source Code (PHP) ]

AJAX is actually not that difficult. All you need to know is some basic XML, and how to iterate through the XML tree structure using Javascript.

As in my previous post, there are two select boxes, City and Country, and the contents of City should reflect that of the selected country. Again, we use the onchange event of Country, but this time, to ask the XMLHttpRequest object to retrieve a generated XML file from the server.

The Javascript to iterate through XML elements and populate a select box is as follows:

var selectBox = document.getElementById("selCity");
...
selectBox.options.length = 0;
selectBox.options[0] = new Option("", "");
if (httpRequest.readyState == 4)
{
    if (httpRequest.status == 200)
    {
        var xmldoc = httpRequest.responseXML;
        var root = xmldoc.getElementsByTagName("cities")[0];
        var elements = root.getElementsByTagName("city");
        for (var i = 0; i < elements.length; i++)
        {
            var value = elements[i].getAttribute("value");
            var text = elements[i].firstChild.data;
            selectBox.options[i + 1] = new Option(text, value);
        }
    }
    else
    {
        alert("There was a problem with the request.");
    }
}

References:

AJAX: Getting Started - Mozilla Developer Center
AJAX/Javascript XML Tips & Tricks

21 January 2007 | Software engineering, AJAX, HTML, Javascript | Comments

Comments:

  1.  
  2.  
  3.