AJAX programming: The XMLHttpRequest object

The central requirement of many dynamic web pages is making a call to the server during the life cycle of that page. Within the AJAX framework, this is accomplished using a component called the XMLHttpRequest object. A minor complication is that, depending on the browser, that object needs to be constructed in different ways. The general sequence for making a call is as follows:

1. Create the XMLHttpRequest object

In theory, creating a simple object sould have been the most straightforward step. Instead, and for fundamentally stupid reasons, it's one of the most complex. The basic way we expect to create the XMLHttpRequest object is as follows:

var reqObj = new XMLHttpRequest();

This is nice, standard JavaScript and works on most browsers except one. Unfortunately, one company decided that they'd try and make a fundamental piece of web functionality work only on their platform. I wonder if you can guess which company that would be...?

In case you haven't guessed, I'll give you a clue. On Internet Explorer, instead of using a standard JavaScript object, the XMLHttpRequest equivalent is implemented as an Active X control1. (An Active X control is a type of embeddable Windows program component.) That means that we have to use some kludgery to detect which method we need to use to create the request object. The general scheme is that if Active X controls are available, we create one of those, else we create the standard JavaScript object:

var xhr;

function createRequestObj() {
  if (window.ActiveXObject) {
    xhr = new ActiveXObject("Microsoft.XMLHttp");
  } else {
    xhr = new XMLHttpRequest();
  }
}

In reality, we'd probably want to modify the above to be a bit more robust: in particular, some browsers simply don't support AJAX (having neither the Active X control nor standard XMLHttpRequest object).

2. Making the call

To make a call to the server, we first specify the URL that we want to connect to with the open() method, passing in the request method. Then, we tell the xhr object the name of the function that should be called when data is received (or a network error occurs). Finally, we call send() to initiate the request to the server:

xhr.open("POST", "/ajaxfunction");
xhr.onreadystatechange = dataProcessingFunction;
xhr.send(data);

Note that we can POST data to the server (typically in XML format), or for simple cases, we could use GET and append some parameters to the URL. In the latter case, we'd just pass null to the send() method.

We pass in a local URL to the site from which the page is loaded. For security reasons:

Browsers won't generally let you make an XMLHttpRequest to a URL from a different host to that from which the page was loaded.

3. Process data in the callback handler

By default, the call isn't made immediately, but rather asynchronously. The send() call returns immediately. Then, some time in the future when a response is received from the server (or a network error occurs), the function that we registered is called— in this example, called dataProcessingFunction(). Without going into all the details just yet, the format of the function is typically to check the so-called ready state of the request and then, if data has indeed been received, to pull it out of the XMLHttpRequest object:

function dataProcessingFunction() {
  // state of 4 means request completed
  if (xhr.readyState == 4) {
    var responseXML = xhr.responseXML;
    // ... process ...
  }
}

In this case, we expect the server to have sent its response in XML format. Alternatively, xhr.responseText would give us the response as a string.

In response to received data, we would typically update an element of the web page with the new data.


1. In terms of the historical sequence of events, I'm being slightly unfair to Microsoft. I believe the Active X control was actually introduced before other browsers then immitated it as a standard JavaScript object. So at the time, MS weren't implementing a then-standard feature in a non-standard way. However, they clearly must have seen what they were adding as "basic functionality" that didn't need to be Windows-specific. Since Active X controls are a Windows-only feature, Microsoft should squarely not have used them to implement such a basic component.


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.