logo
header art

Getting Started with Ajax

June 23, 2005

Handling Server Response
Now that we've sent a request to the server for XML data, we need to process the server's response. As mentioned above, we passed the function notesResponseHandler() to xmlGet(...) to indicate that notesResponseHandler() will be executed when the request's ready-state changes. This function will eventually take the data from notes.xml and display it in the 'notesSection' DIV. The following is the source code to notesResponseHandler():
01 /**
02  * Handler for server's response to notes.xml request.
03  * Notes are pulled from notes.xml and replace the
04  * contents of the DIV with id 'notesSection'.
05  */
06 function notesResponseHandler()
07 {
08     // Make sure the request is loaded (readyState = 4)
09     if (req.readyState == 4)
10     {
11         // Make sure the status is "OK"
12         if (req.status == 200)
13         {
14             var swappableSection = document.getElementById('notesSection');
15             var notes = req.responseXML.getElementsByTagName('note');
16             var str = '';
17             for(i=0; i < notes.length; i++)
18             {
19                 var noteNode = notes.item(i);
20                 if(noteNode != null && noteNode.hasChildNodes())
21                 {
22                     str += noteNode.getAttribute('name') + ': ';
23                     str += noteNode.firstChild.nodeValue + '<br />';
24                 }
25             }
26             swappableSection.innerHTML = str;
27         }
28         else
29         {
30             alert("There was a problem retrieving the XML data:\n" +
31                     req.statusText);
32         }
33     }
34 }
The req object in notesResponseHandler() is the same req object (XMLHttpRequest or XMLHTTP) created in xmlOpen(...). The beginning of the function (lines 8-12) verifies that the response is loaded and there were no problems on the server. Lines 14-26 contain the bulk of the response handling. The responseXML property of req retrieves the server's response as an XML document. On line 15 we get a list of all <note> elements. We then iterate over this list and obtain each notes' name and value (lines 22-23). The contents of the 'notesSection' DIV is then replaced with the note information (line 26).

A description of all methods and properties of the XMLHttpRequest object can be found at W3Schools.

Download Example Source Code