Ajax Fundamentals – Part 2

Index | Part 1 | Part 2 | Part 3 | Part 4 | Part 5

2. Ajax Communication

2.1. Handling the Server Response

The XMLHttpRequest object is used to receive the sever response. Two methods are used, namely responseText and responseXML. The responseText method returns text and the responseXML returns an object that can be parsed as a DOM object.

The responseText is limited however its functionality can be enriched when combining it with the innerHTML property. This is a simple method of including dynamic content within the page. The following code is a selected code extract from an example supplied by Foundations of Ajax.


function startRequest()
{
    createXMLHttpRequest();
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.open("GET", "innerHTML.xml", true);
    xmlHttp.send(null);
}
function handleStateChange()
{
    if(xmlHttp.readyState == 4)
    {
        if(xmlHttp.status == 200)
        {
            document.getElementById("results").innerHTML =                 xmlHttp.responseText;
        }
    }
}


  <body>
    <form action="#">
      <input type="button" value="Search for Today's Activities" onclick="startRequest();"/>
    </form>
<div id="results"></div>
</body>

The above example refers to “innerHTML.xml”. This is a document that contains HTML tags that define an HTML table. When handleStateChange executes, an HTML table is embedded between within ‘results’ div tags and a table will be displayed.The innerHTML property is not a standard therefore not all browsers offer the same support. Microsoft Internet Explorer restricts innerHTML property to read only on certain elements. Using the W3C DOM is the preferred method for manipulating the web page. In order to use the W3C DOM the script needs to extract specific data from the server’s response. Selecting data from XML is far simpler than finding the data in plain text. The script can use responseXML to receive a response in XML format.The responseXML method returns an XML object that meets the W3C DOM specification. This standard is supported by most modern browsers. Using the API provided by DOM, the script can traverse the XML document. The following code shows an example of this.


function showArtistAlbums(artist)
{
    var artistname = artist;
    var xmlDoc = req.responseXML;// req is an XMLHttpRequest object
    var node = xmlDoc.getElementsByTagName(artistname)[0];
    var albums = node.getElementsByTagName("album");
    var result = artistname;

    for(var i = 0; i < albums.length; i++)
    {
        result = result + "\n * " + albums&#91;i&#93;.                         childNodes&#91;0&#93;.nodeValue;// Retrieves the text value
    }
}

&#91;/sourcecode&#93;

The objective of Ajax is to modify only relevant parts of a web page without refreshing the entire page.   This eases the load on the web server and provides a better user experience.   Performing these ‘precision updates' is possible by making use of the W3C DOM. <a href="http://www.amazon.com/Foundations-Ajax-Foundation-Ryan-Asleson/dp/1590595823/ref=pd_bbs_sr_1?ie=UTF8&amp;s=books&amp;qid=1207069447&amp;sr=8-1" target="_blank">Foundations of Ajax gives a good example of dynamically appending rows to an HTML table.   A Sample of the code is shown below.   Note that the tbody tag is used, in this case the tbody element has an ID equal to "resultsBody".



function addTableRow(address, price, comments)
{
    var row = document.createElement("tr");
       var cell = createCellWithText(address);
       row.appendChild(cell);
       cell = createCellWithText(price);
       row.appendChild(cell);
       cell = createCellWithText(comments);
       row.appendChild(cell);
       document.getElementById("resultsBody").appendChild(row);
}
function createCellWithText(text)
{
       var cell = document.createElement("td");
       var textNode = document.createTextNode(text);
       cell.appendChild(textNode);
       return cell;
}

Continue reading

Advertisements