Wednesday, March 14, 2007

Ajax made simple

Any article about Ajax should probably start by explaining that it's not a new programming language. Rather, it's a methodology that enables a greater level of user interactivity in web-based applications. Ajax is based on two languages that have been around for quite a while: JavaScript and eXtensible Markup Language (XML). The "A" in Ajax stands for asynchronous, which literally means, "not at the same time." This is the key that separates Ajax from the classic web page.
In your standard web application model, there is a "back and forth" kind of action. The user requests a web page, the page is served, and in order for the user to see any additional information, he/she must make a separate call for data for more data, which causes (at a minimum) the page to reload. Requests and responses for the new data set occur at the same time, or synchronously.
Using the Ajax methodology, you can add the same level of interactivity to your web-based applications that, previously, was unique to desktop applications. In this model, the user requests a web page and the page is loaded as normal. The difference is that each time the user needs to be presented with more data, a JavaScript makes a call back to the server and retrieves the data in an XML format. This allows the developer to change the content of the page without reloading the entire page. As you can imagine, this can be extremely appealing to the end user. Ok, so lets get started...
In order to fully understand this article, I have to assume that you already have a firm understand of HTML, JavaScript and XML. Teaching these components of Ajax is outside the scope of this article, but you can find some excellent tutorials at
Now, let's describe what you are going to create. We are going to create two select boxes from which we can select a Make and Model of vehicle. The Models that we can select from will be determined by the Make that is first selected.
Aside from the HTML present, you'll need an XML file. If you don't have one handy, you can use the one from this example (20070314.xml). After you have an XML file, you'll need a JavaScript that you can call to load the XML document. For this you can copy the script below:
function ajaxRead(url, method, parameters, functionToRunWithXMLResponse) {
          var xmlObj = null;
          if (document.all) { 
               xmlObj = new ActiveXObject("Msxml2.XMLHTTP"); 
          } else { 
               xmlObj = new XMLHttpRequest(); 
          xmlObj.onreadystatechange = function() {
               if(xmlObj.readyState == 4) {
                    if (xmlObj.status == 200) {
                         eval(functionToRunWithXMLResponse + "(xmlObj)");
                    else {
                         alert("The requested operation returned an error code: " + xmlObj.status + "\n\n" + xmlObj.statusText);
 (method, url, true);
          if (method == "POST") {
               xmlObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
               xmlObj.setRequestHeader("Content-length", parameters.length);
               xmlObj.setRequestHeader("Connection", "close");
          } else {
               parameters = "";  // Just to make sure it was called correctly.
          xmlObj.send (parameters);

The ajaxRead function will access the given URL to read the XML file once it reads the XML file it then passes the XML Document Object to whatever function you specify in the functionToRunWithXMLResponse parameter. Here is an example of how the ajaxRead function should be called:
ajaxRead('/xml/cars.xml', 'GET', '', 'loadMakes');
Once you have the XML Document Object, you can simply crack open the XML document itself with JavaScript using the Document Object Model (DOM) and have your way with the data. In the example above I have chosen to simply load the names of the Makes and Models into a pair of select boxes.
function loadMakes(objXML) {
          // Get a handle on the XML Document Object passed from the ajaxRead function.
          var xmlDoc = objXML.responseXML.documentElement;
          var arrLevelOne = xmlDoc.childNodes;
          var intLength;

          //Populate the Makes
          for (var x = 0; x < arrLevelOne.length; x++) {
               intLength = document.form1.selectMake.options.length;
               document.form1.selectMake.options[intLength] = new Option(xmlDoc.childNodes(x).childNodes(0).text, xmlDoc.childNodes(x).childNodes(0).text);
          document.form1.selectMake.options[0] = new Option("Select a Make", "Select a Make");
          document.form1.selectMake.options.selectedIndex = 0;
The last thing I did to complete the example given was create another JavaScript function that loaded the Models based on make that ran when the onChangeevent fired from the Make select box.
Using this method of web application development, developers can create fully interactive applications that enrich the user's experience and actually change the way your site's visitors think about the web.
Supporting documents:

No comments:

Post a Comment