Simple AJAX Request and Response JavaScript

Here is the simple form of an AJAX call made to an XML document, parsing through the returned document and and grabbing the a specific node from the DOM. There is a try/catch clause to handle the 4 different sets of XMLHTTP objects for different browsers. The callback function is called once the response is returned as 4+200 and the response is rendered to the user. Below is the JavasScript code snippet.

var XMLHttpArray = [
        function() {return new XMLHttpRequest()},
        function() {return new ActiveXObject("Msxml2.XMLHTTP")},
        function() {return new ActiveXObject("Msxml2.XMLHTTP")},
        function() {return new ActiveXObject("Microsoft.XMLHTTP")}
];
function createXMLHTTPObject(){
        var xmlhttp = false;
        for(var i=0; i<XMLHttpArray.length; i++){
                try{
                        xmlhttp = XMLHttpArray[i]();
                }catch(e){
                        continue;
                }
                break;
        }
        return xmlhttp;
}////
function AjaxRequest(url,callback,method){
        var req = createXMLHTTPObject();
        req.onreadystatechange= function(){
                if(req.readyState != 4) return;
                if(req.status != 200) return;
                callback(req);
        }
        req.open(method,url,true);
        req.setRequestHeader('User-Agent', 'My XMLHTTP Agent');
        req.send(null);
}////
function AjaxResponse(req){
        var respXML=req.responseXML;
        if(!respXML) return;
        var respVAL=respXML.getElementsByTagName('family')[0]
.getAttribute('result');
        document.getElementById("status").innerHTML += respVAL;
}////
function ClearResponse(){
        mdiv=document.getElementById("status");
        mdiv.innerHTML = "";
}////
function MakeRequst(){
        AjaxRequest("ajax.xml",AjaxResponse,"get");
}////

And our sample XML file looks like this:

<?xml version="1.0" encoding="utf-8"?>
<family result="successful ajax request &amp; response!">
 <parents>
 <father name="Mike" last="Brady" />
 <mother name="Carol" last="Martin" />
 </parents>
 <children>
  <sons>
   <son>Greg</son>
   <son>Peter</son>
   <son>Bobby</son>
  </sons>
  <daughters>
   <daughter>Marcia</daughter>
   <daughter>Jan</daughter>
   <daughter>Cindy</daughter>
  </daughters>
 </children>
 <maid name="Alice" />
</family>

Here is a working sample of this code.


Some things to note are:

I’m using a GET here, but yo can easily change that to a POST in the call to AjaxRequest.

The URL passed to AjaxRequest can contain parameters as needed.

You can handle other readyStates(0,1,2,3) and HTTP status codes as you wish using the onreadystatechange handle.

I am sending null since I am not posting anything back to the server, but you can swap that with your own Post data if you wish. To set that up you have to also add this line of code before you call send to set the proper request headers.

req.setRequestHeader('Content-type' , 
'application/x-www-form-urlencoded');

The responseXML property is only available when the request is made to an XML document, so If you are using other document types (HTML,Text,CSV,JSON) you will not have access to this property. If you use anything other than XML data you will have access to the responseText property instead.

Once you have the handle to the responseXML property, you can traverse through the XML DOM like you would with any other DOM object and you can use all the DOM element methods, properties and events that you already know.

For example to get a list of all the sons in the family we can do:

respSONS=respXML.getElementsByTagName("son");
respSonVals = "";
for(x=0; x<respSONS.length; x++){
    respSonVals += " " + respSONS[x].firstChild.nodeValue;
}

Try Get Son Names

Results Go Here:

Leave a Reply

Your email address will not be published. Required fields are marked *

Visited 19683 times, 4 so far today