-->
Bookmark and Share

Getting Started with AJAX

See the HttpRequest.js source code.

The HttpRequest Object

To make the XMLHttpRequest object a little easier to use we can create a user-defined JavaScript object to replace it. This new object will basically be a wrapper for XMLHttpRequest that hides the browser differences in instantiating the object and simplifies the process of making a request and obtaining the response.

Below is an overview of the HttpRequest object:

HttpRequest Object
Constructor
HttpRequest() Creates a new instance of the HttpRequest object.

Notes: Be sure to set the url property before calling get() or post(). Likewise, if you want to process the response, set the successCallback property. To process errors on an unsuccessful request, set the failureCallback property (see below).
Properties
successCallback A function to be called when a GET or POST request completes successfully (i.e., the HTTP status is "200 OK"). The function should accept one argument which will be the HttpRequest object that made the request.
failureCallback A function to be called when a GET or POST request completes unsuccessfully (i.e., the HTTP status is anything other than "200 OK"). The function should accept one argument which will be the HttpRequest object that made the request.
url The URL to send the request to. This should not include a query string.
queryString A query string to append to the URL.
username Username for authentication, if required.
password Password for authentication, if required.
status,
statusText,
responseText,
responseXML
These are equivalent to the XMLHttpRequest properties of the same name.
Methods
clearRequestHeaders() Removes all request headers.
get() Performs an asynchronous GET request.
post(data) Performs an asynchronous POST request, passing the given data. Be sure to set the "Content-Type" request header appropriately prior to calling post().
abort(),
setRequestHeader(name, value),
getResponseHeader(name),
getAllResponseHeaders()
These are equivalent to the XMLHttpRequest methods of the same name.

To see the difference between this object and the native XMLHttpRequest object, let's look at the code needed to POST some data to the web server and retrieve a response using the XMLHttpRequest object:

// Create an XMLHttpRequest object using our cross-browser function.
var myRequest = getXMLHttpRequest();

// Assign an onreadystatechange handler.
myRequest.onreadystatechange = myReadyStateChange;

function doPost()
{
  // Create the post data.
  var data = "...";

  myRequest.abort();
  myRequest.open("POST", "http://www.example.net/script/getXML.pl", true);
  myRequest.setRequestHeader("Content-Type",
    "application/x-www-form-urlencoded");
  myRequest.send(data);
}

function myReadyStateChange()
{
  if (myRequest.readyState == 4)
  {
    if (myRequest.status == 200)
    {
      processResponse(myRequest);
    }
    else
    {
      showError(myRequest);
    }
  }
}

function processResponse(httpRequest)
{
  ...
}

function showError(httpRequest)
{
  ...
}

Note that we have to call the abort(), open(), setRequestHeader() and send() methods on every request. Also, as mentioned earlier, any request headers must be set after the call to open() and before the call to send().

Within the onreadystatechange handler we first need to check the ready state determine if the request has been completed and then check the status code to determine if it was successful (i.e., HTTP 200 OK).

Now look at the code required to do the same thing using an HttpRequest object:

// Create an HttpRequest object.
var myRequest = new HttpRequest();

// Assign callback functions, URL and set request headers.
myRequest.successCallback = processResponse;
myRequest.failureCallback = showError;
myRequest.url = "http://www.example.net/script/getXML.pl";
myRequest.setRequestHeader("Content-Type",
  "application/x-www-form-urlencoded");

function doPost(event)
{
  // Create the post data.
  var data = "...";

  myRequest.post(data);
}

function processResponse(httpRequest)
{
  ...
}

function showError(httpRequest)
{
  ...
}

Note that there is no need to call abort(), open(), setRequestHeader() and send() on each request, instead we just call get() or post().

A call to get() or post() automatically aborts any currently active request for that instance of the object. Request headers can be set just once, so long as we do it before calling get() or post(). Similarly, the URL can be set just once, it doesn't need to be specified on every individual request via open().

Lastly, the HttpRequest object handles the onreadystatechange event internally and only does one callback, when the request completes. This callback will be to either the function specified on the successCallback property if the request successfully returns a response (i.e., the status is HTTP 200 OK) or to the function specified by failureCallback (if the status is anything else).

Note that the terms "successCallback" and "failureCallback" are relative to the HTTP status on the response. All "success" means is that the server was able to process the request and return a response. You may not have gotten the response data you expected. Likewise, "failure" may be OK if you were simply trying to determine if a particular web page existed and it returned "404 Not Found."

Now let's see how to use this new object.