Using Ajax in your website

By | March 7, 2009

I noticed something when I went through the posts I created on this blog. I have been raving for and against Ajax in several posts. Ranging from whether or not you should include Ajax for usability, how to work with Ajax in combination with forms and my personal favorite if you should use Ajax at all. Please keep in mind that this last post is really old already and probably a bit outdated.

Looking through all of these posts I noticed that even though I talked quite some bit about Ajax I never actually gave any examples of how to implement it. So today I will correct this mistake 😉

A simplified explanation of what Ajax is

It’s probably best to first give a very brief explanation of what Ajax is and how you could use it to create more dynamic and user interactive web pages. So what is Ajax actually. Well in a nutshell it’s a JavaScript implementation of communicating between the browser and the web server without having to reload an Internet page.

You can create a good impression of how it works by thinking about this as follows. In an traditional website each action a user takes will cause the browser to call a page on the web server. The web server then generates the full HTML for that page and returns it to the browser. This is visible to the user as the page they are looking at will ‘refresh’. Ajax is a technique to call the web server without reloading a page or redirecting to a new page. Hence fetching new content to an already displayed page in the browser. See the image below for a graphical overview of the communication between the browser and the web server during a typical Ajax call.

Ajax Interaction diagram

This gives you the change to greatly enhance your existing website with new features. Loading in content area’s on the fly. Submitting forms to the server without having to redirect the user, you name it and you can do it with Ajax. There are some limitations, but most of those are covered in my initial articles on this blog.

Multiple browsers, multiple problems

One of the first things I should probably try and explain is that every browser seems to have a different way of implementing the Ajax object. On its own this is not a big issue, but you need to keep track of this fact when you build some form of Ajax functionality in your website.

So creating the Ajax object needed to perform these calls to the web site has to be done with some try and catch work. Below is an example of how to create the Ajax object, supported by most of the popular browsers. In the example we first try and create the Ajax object for the Internet Explorer, which uses ActiveX objects.

try {
  // try to allocate the ActiveX object used by Internet Explorer
  this.xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
  try {
    this.xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (e) {
    this.xmlHttp = false;
   }
}

if (!this.xmlHttp && typeof XMLHttpRequest!='undefined') {
  // fallback for Firefox and other Mozilla based clients
  this.xmlHttp = new XMLHttpRequest();
}

After executing this code (keep in mind it is JavaScript so put it in a script block in the HTML) you should have the Ajax object available in this.xmlHttp. It may be useful to know a little more about the object functions before continuing the example. The Ajax object has the following functions:

  • .status,
    returns the current status of the page. This is after the result is returned from the web server. (Status 200 is good)
  • .responseText,
    contains the result that was sent by the webserver after the url was called
  • .open(protocol, url, asynchronized),
    will open the connection to the web server and start the call
  • .onreadystatechange,
    the event that gets triggered by the Ajax object during the call to the webserver. This will be called multiple times, especially in Internet Explorer. (Possible status: 2 = busy, 4 = done)
  • .send,
    send the request to the server and wait for the result (or not if asynchronized call was selected)

A basic call to the webserver

After initializing the Ajax object you can perform any call to the webserver you’d like. The example below will show you how to open an web page and display the result into a message box. What the content is that is returned is not relevant for the functioning of the example.

this.xmlHttp.open('GET', 'http://www.example.com/page.html', false);
this.xmlHttp.onreadystatechange = function() {
  if (self.xmlHttp.readyState == 4) {
    alert(self.xmlHttp.responseText);
  }
}
this.xmlHttp.send(null);

As you can see this is a very basic example, but it does show exactly how to use the Ajax technology. You can apply this logic for loading in new content on the fly, or just preloading some stuff.

Leave a Reply