XmlHttpRequest

Posted on 2010-03-31 23:10 in Blog

I was reading about Websockets and their usefulness the other day when I realized how little of their precursor, the XmlHttpRequest, I actually knew. I performed some research and code a few quick and dirty example pages and discovered a new realm of capabilities that I was previously ignorant about.

For years, I had assumed AJAX technology was only useful if there were server side scripts interpreting the requests, gathering the needed data, and returning well formatted responses. These responses were then used to update the page content.  While coding one of the examples, I had an ‘Ah-ah moment’.  AJAX capabilities could be utilized to load static content when updating the page.  Instead of having to address PHP or ASP pages, plain old HTML files could be the target.

Within minutes, I had seamlessly written a basic homepage, consisting of several sections that loaded all the content without a single page refresh. This game me a liberating feeling. Now I can update the content without losing my JavaScript variable values.

Quick Example

The simplest way to dynamically load content is to specify

/* Create the request object */  
if (window.XMLHttpRequest) {        // Modern browsers  
    xhttp = new XMLHttpRequest();  
} else {                            // Old Internet Explorer  
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");  
}
/* Perform the request */  
xhttp.open("GET","external\_file.txt",false);  
xhttp.send("");  
destinationElement.innerHTML = xhttp.responseText;

This creates a new XmlHttpRequest object across multiple browser types.  The ‘open’ command defines how the file will be retrieved (GET vs. POST) and the URL for the file.  Send performs the actual communication with the server.  After the communication is complete, responseText is extracted and displayed to the user.

This block of code is very straightforward and very misleading.  It performs no error handling (file not found) and does not take into account the amount of time needed to retrieve file (server load).

Better Example

A better approach would be to use a JavaScript library that is designed for this type work, JQuery.

$(".destinationElement").load("external_file.txt");

This single line of JavaScript performs the same function as the block of code above. It says load the contents of the files, external_file.txt, into the DOM element whose title is ‘destinationElement’.

Again, this over looks the same errors the first block contained, errors while loading the file and what not.  Luckily, JQuery has built in error handling events. As a programmer, we can define what action should be taken when a query fails.

$(window).error(function(msg, url, line){  
    // handle the error  
});  

Quick note: The above block will catch all errors that occur, not just errors AJAX errors.