Unintentionally Blank

Phil Nash on the Internet, Web Standards and Accessibility

Learning AJAX: Lesson 3 - XMLHttpRequest

Jul 12, 2007

by Phil Nash

After setting out the groundwork for my AJAX example by creating a random quote generator in PHP then using the DOM to add a link that will perform the AJAX function, I am now ready to start communicating with the server and loading up data without refreshing the page. To do so I need to get to grips with the XMLHttpRequest object.

A Bit Of Background

XMLHttpRequest is not yet a W3C standard, but there is a working draft. It was first implemented by Microsoft in Outlook before making its way to Internet Explorer 5 as an ActiveX Object. Then the Mozilla project got their hands on it, implementing it as a native browser object in Mozilla. The other browsers fell in line soon after. It is now the basis of AJAX and powers most of the web applications available online today.

Sadly, even having pioneered this object, Microsoft's Internet Explorer tends to make life difficult for developers because XMLHttpRequest is an ActiveX object (except in IE7 where it is now a native object). To create one you need the following javascript:

var XHR = new ActiveXObject("Microsoft.XMLHTTP");

All other browsers that support XMLHttpRequest require the following:

var XHR = new XMLHttpRequest();

Once you have your XMLHttpRequest object, the methods are all the same, so it is best to create a function that returns one regardless of browser. I have done this using try and catch, try to create the native object first and, if that doesn't work, the ActiveX version, if neither work I am going to return false so that I can halt the script in another part.

Cross Browser XMLHttpRequest

function XHR() {
  try { // try the native object
    return new XMLHttpRequest();
    }
    catch(e) {
      try { // then try the ActiveX object
        return new ActiveXObject("Microsoft.XMLHTTP");
       } catch(e) { return false; }
      }
  }

The final part of this mini series will be posted shortly, where I finish off my example by using the XMLHttpRequest to get my data from the server.

Unintentionally Blank is Phil Nash's thoughts on web development from 2006-2008. Any code or opinions may be out of date.