CodeinWP CodeinWP

Ajax From the Ground Up: Part 1 – XMLHttpRequest

Ajax From the Ground Up - Part 1It started out as an industry “buzzword” and has slowly progressed into one of the most important web technologies in use today. It is easily implemented using your favourite JavaScript framework. It can provide a beautiful layer of enhancement to many web applications, helping to improve page-load times and greatly improve the user experience. It can also degrade the user experience and cause a web application to fail if a particular client-side technology is unavailable.

Yes, I’m talking about the web methodology immortalized by Jesse James Garrett called Ajax. (As Garrett points out, Ajax is not a technology, but several technologies.) This article will begin a multi-part tutorial series in which I will explain how to implement Ajax “from the ground up”. This series will be geared towards web developers who would like to better understand Ajax in its raw format, using pure JavaScript.

This series will benefit developers who have so far gained the following understanding of Ajax:

  • Ajax is more than just a buzzword; it’s a web development mainstay
  • Web applications should not depend on Ajax for core functionality; thus
  • Ajax should be viewed as a way to enhance the user experience in an already functional web application

Further understanding of the above points can be easily gleaned from a number of online articles and books published in the 5 years since the appearance of Garrett’s article mentioned above. So, I’m not going to spend any time on those principles, but strongly suggest you understand those 3 points before you go through this tutorial series.

This series is going to show you how to build an Ajax application from the ground up, using raw JavaScript. So, let’s get right into writing the code that drives one of the most popular development methodologies in use today.

The XMLHttpRequest Object

Everything done with Ajax centers around the use of the XMLHttpRequest object. In order to accomplish an Ajax request (that is, in order to communicate between the client and the server “asynchronously”), we need to create an instance of the XMLHttpRequest object. Since the advent of Internet Explorer 7, most current browsers agree on the method used to instantiate this object.

Here is how most browsers do it:

var xhrObject = new XMLHttpRequest();

The above code is using the standard method for creating an object instance in JavaScript, so if you’re already familiar with object-oriented development concepts, you’ll have no problem understanding that line of code. Basically, we’re creating an instance of the XMLHttpRequest object using the “new” keyword, and placing that object in the appropriately-named xhrObject variable.

However, Internet Explorer versions 6 and lower (no surprise!), do it using one of the following two methods, instantiating an ActiveX object instead:

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

It would be nice to be able to include those 3 different methods, one after the other, and let the browser decide which one to use — but it’s not quite that simple. IE5/6 will produce an error with the first method, and the other browsers will produce an error with the IE5/6 method. So we need to use object detection in conjunction with a try-catch construct to ensure that a successful method is detected without throwing an error.

A Cross-Browser Function for Creating the Object Instance

Here is a function that combines all three possibilities and will not throw an error, even if none of the methods are supported:

function getXhrObject() {
  var xhrObject = false;
  // Most browsers (including IE7) use the 3 lines below
  if (window.XMLHttpRequest) {
    xhrObject = new XMLHttpRequest();
  // Internet Explorer 5/6 will use one of the following
  else if (window.ActiveXObject) {
    try {
    xhrObject = new ActiveXObject("Msxml2.XMLHTTP");
      } catch(err) {
        try {
        xhrObject = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(err) {
        xhrObject = false;
  return xhrObject;

Don’t be too overwhelmed with the above code. Here is a run-down of it: Line 2 assigns an initial value of false to the xhrObject variable. Lines 4-6 test for the existence of a native XMLHttpRequest object, which is how most browsers will handle Ajax requests. If the object is successfully detected, then the instance is created, the rest of the function (lines 8-18) is ignored, and the value of the xhrObject variable is returned.

If the user’s browser does not support the native XMLHttpRequest object (lines 4-6), then lines 8-18 will try two other methods to instantiate the object. First, the entire “IE5/6” section is wrapped in an if statement that checks to see if the user’s browser supports ActiveX. If it is not supported, then the xhrObject variable will return a value of false.

If ActiveX is detected, a try-catch construct is used to ensure that an ActiveX object for Ajax exists. In other words, it’s possible — though very unlikely — that a browser could support ActiveX, but not Ajax. The beauty of the try-catch method is that it will “catch” any errors without displaying them to the user.

Now we have a function that will ensure that a user’s browser will not throw an error when trying to detect Ajax capabilities.

Test for Ajax Functionality By Calling the Function

Using the getXhrObject function, we can easily decide whether actual Ajax requests can be implemented. Here’s how:

var ajaxCapable = getXhrObject();
if (ajaxCapable) {
  // perform some Ajax functionality here

Remember that the getXhrObject function “returns” a value. So, the first line above will assign the result of the getXhrObject function to the variable ajaxCapable. Then, we use an if statement to check if the variable has a non-false value. Technically, we could write it like this:

var ajaxCapable = getXhrObject();
if (ajaxCapable !== false) {
  // perform some Ajax functionality here

The second example above is a more literal way of coding the previous example. The first example is cleaner, even though the second example might be easier to understand. For our purposes, we’ll use the first example.

Summary of Part 1

That’s it for part 1 of this series. So far we’ve covered a couple of very basic things to get us started coding Ajax with raw JavaScript. We learned how to:

  • Instantiate the XMLHttpRequest object in a cross-browser fashion that will not throw an error when Ajax is not supported
  • Create a reusable function that will easily allow us to detect an Ajax-capable browser

Stay tuned for part 2 which will show you what to do once you’ve created an instance of the XMLHttpRequest object.

In the meantime, you can view a demo of the code we’ve created so far, or download it for your own use using the buttons below.

5 Responses

  1. rizza says:

    Can’t wait to see Part 2

  2. Kim H says:

    Very interesting; I’ve never really messed with Ajax that much (well, aside from the brand of soap), but in terms of this post, this is definitely a good way to get your feet wet. Thanks for this look into it; I look forward to reading part two in Reader probably tonight.

    Of course, web 2.0 itself has plenty of “buzzwords”; it, in and of itself, could even possibly be considered one. :)

  3. sfondi says:

    Nice tutorial!

  4. Great thanks! this series will help me a lot…………… :-)

  5. smith says:

    nice post! Though I wanna know about Ajax , I couldn’t find a good article.
    But now …. thanks for ur post.

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field and deep URLs are not allowed in the "Website" field. If you use keywords or deep URLs, your comment or URL will be removed. No foul language, please. Thank you for cooperating.

Markdown in use! Use `backticks` for inline code snippets and triple backticks at start and end for code blocks. You can also indent a code block four spaces. And no need to escape HTML, just type it correctly but make sure it's inside code delimeters (backticks or triple backticks).