XMLHttpRequest

2006-12-20


XMLHttpRequest and AJAX

XMLHttpRequests(XHR) are the core of AJAX. The XHRs allow a browser to asynchronously request a new webpage and return some value without having the current page refresh itself. The updating of the current page is done with various javascript functions that I will discuss later in this article. For now, let's see how to create an XHR.

Creation of XMLHttpRequest Object

As is probably expected with the incompatibility between browsers, we will need to create different objects for different browser cases. Here is the code that will create a XHR regardless of what browser you are using.

var xmlhttp;
if(window.XMLHttpRequest) {
   xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
   xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
return xmlhttp;

Using the XHR

Great... now you've created an object now what? You have to create a javascript function that will open your XHR and request a web document. (note, xmlhttp = httpRequestObject)

httpRequestObject.open("GET", "htmlfile.php", true);
httpRequestObject.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
httpRequestObject.onreadystatechange=callback;
httpRequestObject.send(null);
}


Why am I setting the RequestHeader to Jan 1st 2000? Well, this took me a long time to figure out, because Firefox was grabbing the file correctly, but for multiple requests in IE, the script was not working. The problem is that IE caches the previous request, and won't check to see if the html page you are requesting has changed. Thus, it will not grab the page more than once. By expiring the html header, it forces IE to grab the page everytime and ignore whatever it has already cached.

The Callback

The callback function is the final piece of the puzzle. The callback function is initiated when the XHR returns with information from the webpage it has requested asynchronously. if(httpRequestObject.readyState==4) {
   var response = document.getElementById('response');
   var responseText = httpRequestObject.responseText;
   response.innerHTML = responseText;
}


And that's it. The example above takes the response text from the ajax call and modifies the current Id on the page on the fly.