Bookmark and Share

Getting Started with AJAX

See the AJAX entry on Wikipedia for more information.

This article covers some basics of AJAX and, more specifically, how to use the XMLHttpRequest object in JavaScript to dynamically update web pages using data retrieved from the web server.

What is AJAX?

AJAX stands for Asynchronous JavaScript And XML. It involves the type of DHTML coding covered elsewhere on this site to dynamically update web pages but it adds an extra piece: communicating with the web server to send and retrieve data without loading a new page or reloading the current page.

To do this, the XMLHttpRequest object is used. This object is supported by most modern browsers in one form or another. As the name implies, the object allows you to perform HTTP requests which returns some form of response. The XML part refers to the fact that the object can automatically parse an XML document sent in response to a request.

The idea is not new. Hidden IFRAMEs have been used to do the same thing. But the XMLHttpRequest object is more flexible and simplifies the process.

HTTP

As mentioned, the XMLHttpRequest object allows you to perform HTTP requests. So a quick overview of HTTP is in order.

When you load a web page in your browser, say "http://www.example.net/about/index.html", the browser first opens a connection to the host, www.example.net. It then sends the server an HTTP request which consists of several lines of plain text. A typical request may look something like this:

GET /about/index.html HTTP/1.1
Host: www.example.net
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.12)...
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,...
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Proxy-Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

The first line contains the HTTP verb or method. In this case, the method is GET which means return the following document. Following that is the path to the document to retrieve (/about/index.html). The HTTP/1.1 tells the server what version of HTTP the browser supports.

The lines that follow are called request headers. The specify additional information that may be used by the web server to help it send a proper response to the browser.

The web server will return a response. Like the request, this consists of several lines of plain text. A typical response to the above request will look something like this:

HTTP/1.x 200 OK
Server: Microsoft-IIS/5.1
Date: Fri, 20 Jan 2006 19:29:47 GMT
Content-Length: 534
Content-Type: text/html
Cache-Control: private

<html>
<head>
<title>About Us</title>
</head>
<body>
<h1>About us</h1>
<p>...</p>
</body>
</html>

The first line contains the HTTP version and a three digit status code. The text following that number is a short description of that code. 200 means "OK," the request was successfully processed. If the requested page did not exist, the status would be "404 Not found."

The lines following are response headers. Like the request headers, these give additional information about the response such as the document type ("text/html") and size (534 bytes).

A blank line follows, signaling the end of the response header. The rest of the lines represent the response data. In this case, it is the HTML of the page which the browser will parse and render.

Passing Data in an HTTP Request

There are two commonly used ways for a client to pass data in an HTTP request. One is to append a query string to the URL. For example,

http://www.example.net/signup.asp?name=Jane+Doe&email=jane%40myhost.com

Note the format of the query string data. Each field is represented as name=value and fields are separated by a '&' character. This is commonly done as it allows the web server to parse the individual fields.

Also, each name and value is url-encoded (spaces are replaced with a '+' sign, non-alphanumeric characters are replaced by a hex value in the form "%xx"). This encoding is necessary due the the restricions on characters allowed in an URL.

The second way to pass data on an HTTP requuest is to use the "POST" method. This is often used with forms on web pages. An example of a POST request generated when a user submits a form is shown below:

POST /signup.asp HTTP/1.1
Host: www.example.net
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.12)...
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,...
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 38

name=Jane+Doe&email=jane%40myhost.com

Note the empty line following the request headers. This marks the end of the headers section and the start of the data section.

The data is in the same format as with the query string example above. In the headers section, the "Content-Type" and "Content-Length" fields inform the web server of the data format used and the amount of data being submitted.

The XMLHttpRequest Object

With the XMLHttpRequest object, you can make HTTP requests like those above from within JavaScript code on a web page and access the data returned by the web server.

We'll see an example shortly but first, here is a list of the object's properties, methods and events that will be used:

XMLHttpRequest Object
Properties
readyState A number representing the current state of the request:
  • 0 - UNINITIALIZED
  • 1 - LOADING
  • 2 - LOADED
  • 3 - INTERACTIVE
  • 4 - COMPLETE
status The numeric HTTP status code returned by the web server.
statusText The text associated with the above HTTP status code. For example, 200 means "OK" and 404 means "Not found".
responseText A string containing the response data returned from the web server.
responseXML If the web server returns an XML document, this will be a DOM document object representing the parsed XML.
Methods
open(method, url, asynch, username, password) Initializes a new request. method is the HTTP request verb, usually "GET" or "POST". The last three options are optional: asynch defaults to true, username and password may be specified if the web server requires authentication.
setRequestHeader(name, value) Sets a the named request header.
send(data) Makes the request. optionally passing data.
abort() Aborts an active request.
getResponseHeader(name) Returns the value of the named response header.
getAllResponseHeaders() Returns a string containg all the response headers.
Events
onreadystatechange Raised anytime the readystate property changes.

Before you can use the XMLHttpRequest object, you need to create an instance of it. There currently is no standard for it but many modern browsers support the XMLHttpRequest object natively. IE, of course, is an exception. To be fair, Microsoft introduced the idea, but implemented it as an ActiveX object.

The code below can be used to create an XMLHttpRequest object despite the browser differences. It also defines some constants that will help when using the object.

//
// Define a list of Microsoft XML HTTP ProgIDs.
//
var XMLHTTPREQUEST_MS_PROGIDS = new Array(
  "Msxml2.XMLHTTP.7.0",
  "Msxml2.XMLHTTP.6.0",
  "Msxml2.XMLHTTP.5.0",
  "Msxml2.XMLHTTP.4.0",
  "MSXML2.XMLHTTP.3.0",
  "MSXML2.XMLHTTP",
  "Microsoft.XMLHTTP"
);

//
// Define ready state constants.
//
var XMLHTTPREQUEST_READY_STATE_UNINITIALIZED = 0;
var XMLHTTPREQUEST_READY_STATE_LOADING       = 1;
var XMLHTTPREQUEST_READY_STATE_LOADED        = 2;
var XMLHTTPREQUEST_READY_STATE_INTERACTIVE   = 3;
var XMLHTTPREQUEST_READY_STATE_COMPLETED     = 4;

//
// Returns XMLHttpRequest object.
//
function getXMLHttpRequest()
{
  var httpRequest = null;

  // Create the appropriate HttpRequest object for the browser.
  if (window.XMLHttpRequest != null)
    httpRequest = new window.XMLHttpRequest();
  else if (window.ActiveXObject != null)
  {
    // Must be IE, find the right ActiveXObject.
    var success = false;
    for (var i = 0;
         i < XMLHTTPREQUEST_MS_PROGIDS.length && !success;
         i++)
    {
      try
      {
        httpRequest = new ActiveXObject(XMLHTTPREQUEST_MS_PROGIDS[i]);
        success = true;
      }
      catch (ex)
      {}
    }
  }

  // Display an error if we couldn't create one.
  if (httpRequest == null)
    alert("Error in HttpRequest():\n\n"
      + "Cannot create an XMLHttpRequest object.");

  // Return it.
  return httpRequest;
}

We can then define an XMLHttpRequest object like so,

var myXmlHttpRequest = getXMLHttpRequest();

Now let's see how to use it.