Ajax Tutorial

So let's have a look at using Ajax. Ajax is based around the XmlHttpRequest javascript object. Most modern browsers support this object or a similar object. (I haven't yet found one that doesn't.) To create the object, just instantiate a new instance in your javascript as shown below.

var req = new XMLHttpRequest();

As always, IE has to be diffferent. To create the XmlHttpRequest object in IE, use one of the following code snippets.

var req = new ActiveXObject("Msxml2.XMLHTTP");
var req = new ActiveXObject("Microsoft.XMLHTTP");

So as you can see, in IE you have to create an ActiveX COM object.

The nice thing about javascript is you don't have to do browser sniffing (and you shouldn't!). Instead, you can do capability sniffing. With the above example we can nest each attempt at creating the request object in a try catch block, going from the most general case to the most specific.

var req = null;
try
{
  req = new XMLHttpRequest();
}
catch(e)
{
  try
  {
    req = new ActiveXObject("Msxml2.XMLHTTP");
  }
  catch(e)
  {
    try
    {
      req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch(e)
    {
      req = null;
    }
  }
}

Making requests

Now we have the request object we can make a request to the server for some data. We use the open method of the request object to prepare for the request, then call the send method to invoke the request. This request can be either inline (synchronous) or callback (asynchronous). The third parameter of the open method controls this behaviour.

req.open("GET", url, false);
req.send();

In the above example we're making a GET request to the url stored in the variable url and we'll invoke this request synchronously so the thread will block while the call is made. To invoke the request asynchronously we need to provide a callback method or event handler for the onreadystatechange event.

req.open("GET", url, true);
req.onreadystatechange = function() { changeStatus(req); };
req.send();

In the above example we assign the function changeStatus, which expects a single parameter which is the request object, as the changed status event handler. When we invoke send this time the thread will not block. But we must make sure we declare the changeStatus function.

function changeStatus(req)
{
  // method body
}

So now that we've made a request, how do we get the data? When the request returns, the data is stored in the request's responseText property. However, we shouldn't try accessing this property until we're sure the request has completed. We can check the request's status using the readyState property.

A value of 4 indicates the request is finished and the responseText property contains the returned data. Another property we may be interested in is the status property. The status property contains the HTML return code the server sent back. A value of 200 is success. The code below shows how we can make sure the request has completed and was successful before continuing.

while(req.readyState != 4)
{
  if(req.status == 200)
  {
    // process data
  }
  else
  {
    // error handling
  }
}

So now we can use the data.

var data = req.responseText;

Sending data

We can also send data to the server, not just retrieve it. We provide the data in the send method as a series of key value pairs as you would do for a query string.

req.send("akey=avalue&bkey=bvalue");

It greatly depends on the language and framework used on the server as to how to access this data on the server. In many cases it is easier to submit the data to the server as form data. To do so, we need to set the encoding type of the request.

req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

The above code sets the content type as form data. Now we can access the data posted to the server on the server-side using the forms array / collection exposed from the request by the framework we're using on the server. Just make sure to set the content type before making the call to send.

c