An Introduction to AJAX

1 - I can do better 2 - Jury's out 3 - Pretty darn good 4 - Splendiferous 5 - Awesometastic by 8 people | Log in to rate

Ranked #2,118 in Tech & Geek, #51,068 overall

An overview of AJAX for managers, developers, hobbyists and the curious.

This is a plain-english introduction to Ajax, some of the pitfalls to look out for, links to some Ajax resources and an quick look at writing some simple some Ajax javascript code.

By Nathan Ridley (ERSYS Group)

AJAX Overview 

Understanding the AJAX Concept

AJAX is an acronym that stands for "Asyncronous Javascript And XML". For those less technically inclined, AJAX is a technique, not a product or a brand.

AJAX techniques are used to allow a website to communicate with the server without having to load a new page into the browser. By communicating with the server while the page is still loaded, data can be retrieved and dynamically inserted into the existing page. In the same vein, elements can be removed from the page, or altered as required.

By allowing a page to communicate with the web server without being reloaded in full, it is possible to create faster and more responsive user interfaces than is possible using the traditional model whereby a new page is loaded with each request by the user.

Why is AJAX not in widespread use already? 

AJAX techniques are starting to enter mainstream use at the moment, however this is due to adoption of AJAX techniques by prominent presences on the web such as Google.

Google's GMail and Google Maps services both employ heavy use of AJAX techniques as part of their user interfaces, and as such, have created much fanfare in the web community.

In actual fact, AJAX techniques have been around for a few years, but simply have not been in widespread use due to both a lack of realisation that such capabilities existed and the fact that a certain percentage of users did not have browsers which supported the technology required by AJAX techniques. This has changed now, and more than 99% of all web users are using browsers that support the required technology.

Downsides and Pitfalls 

Potential traps to consider when investigating AJAX

There are several problems with AJAX in the current web environment, and they are as follows.

First, AJAX techniques break the browser out of its traditional role as a viewer of static pages of content and force it behave as an application platform. As a result, this creates usability issues where the user expects to be able to use the browser's "back" button in order to return to a previous state. Because no new page is loaded when an AJAX call is made to the web server, no information is added to the browser's history and thus the back button cannot be used to return to the previous state that the page was in.

An example of the back button problem was the early release by Microsoft of a product dubbed "Windows Live". This product functioned in a similar fashion to Google's personalised homepage, but relied more heavily on AJAX concepts. When a user performed a web search, the results would be dynamically loaded into a section of the page and the user could start clicking around to explore those results. The problem was when the user finished with a specific result and used the back button to return to the search results. As the results had been dynamically loaded without loading a fresh page, the user would be returned to the original Windows Live page, thus eliminating their search results. A frustrating experience to say the least.

Another downside is the fact that AJAX relies soley upon JavaScript calls in order to function at all. This is a problem because search engines do not pay any attention to the JavaScript on a page, and thus any content which is only accessible via an AJAX call will not be indexed and thus will not be found during a web search.

Should I use AJAX? 

Weighing up pros versus cons

In particular, AJAX is very good for implementing systems where search engine indexability is not a prerequisite, for example in user interfaces designed for updating the website's content. When updating a website using one of these "content management systems", there can be several hundred requests to the server during a single session, which makes use of AJAX techniques great for creating a responsive, intuitive experience for the user. Despite the potential traps awaiting those lacking an understanding of the web environment, the benefits to websites utilising AJAX can be significant.

Some Initial Links 

(While I compile a better list)

Ajax: A new approach to web applications
The original article by Jesse James Garret of Adaptive path. This article coined the term AJAX, which has now become a common acronym.
AJAX - Getting Started
Information from the Mozilla Developer Center on how to get started with AJAX.
Ajax.Net - An Implementation for the .Net Framework
A popular and robust .Net-based implementation of the AJAX concept.
SAJAX - Simple Ajax Toolkit for PHP
A popular toolkit for writing AJAX applications for the PHP web scripting language. Also supports Perl, Python and others.
AJAX Programming - Wikipedia Article
A detailed overview of the AJAX concept at Wikipedia.
Mastering Ajax, Part 1: Introduction to Ajax
An in-depth look at getting started writing a basic AJAX communications layer. By Brett McLaughlin, Author and Editor, O'Reilly and Associates
Ajax Camp
An Ajax discussion forum. It's still new but we are watching it closely so if you have any questions or want to talk about anything Ajax-related, come post and we'll respond.
Yahoo! UI Library
An AJAX library and a collection of related user interface code to streamline the AJAX application development process. These have been released by Yahoo free for personal or commercial use.

Popular AJAX Links from Del.icio.us 

Del.icio.us is a heavily used social bookmarking community. This list provides the current 10 most popular links to AJAX-related websites.

Loading Fetching RSS feed... please stand by

Let's Write Some Ajax Code (Part 1) 

A very simple step-by-step Ajax library you can write yourself

Ajax works using an object called XMLHttpRequest. This object is made available to your javascript code automatically by the browser. How you access it depends on the browser you're using. For Internet Explorer you have to do the following:

var myObj = new ActiveXObject('Microsoft.XMLHTTP');

In FireFox and other browsers, there's a native object already, so you can use the following code:

var myObj = new XMLHttpRequest();

We can wrap all of this up in some code that will always give you the right object, regardless of browser. The code is:

if(typeof XMLHttpRequest == 'undefined')
    XMLHttpRequest = function() {
        try { return new ActiveXObject("Microsoft.XMLHTTP"); }
        catch(ex) { return null; }
    }


Now to create an XMLHttpRequest object, you can do it the Firefox way even if you're using Internet Explorer. Ok, so now that we have our object, what do we do with it? First you need to specify which page on your website you'd like it to call. Let's assume you've got some page called getBookTitle.php. This page takes an ISBN as a parameter which you have to post to the page, and it returns the title of the book containing the ISBN.

You can call the remote page either syncronously (Browser freezes until the response is received) or asyncronously (browser keeps going while the call is made, and "calls you back" when it has a response). Seeing as I'm all for a great user experience, let's do it asyncronously, because nobody likes an unresponsive browser.

Let's Write Some Ajax Code (Part 2) 

The callback function and opening the connection

First we need to define a function that is to be executed when we get a response from the server. When the response is received, the server will call this special function and pass it a reference to the request object, and the response text will be stored in the responseText member variable of the XMLHttpRequest object you created. In addition, you'll need to check the readyState value of the request object, because sometimes your function will be notified every time the request object gets some of the data from the server. We only care when all of it has been received, because that means the call has completed. The value when the call is complete is always 4. Here is the function code:

function ShowBookTitle(requestObject) {
    if(requestObject.readyState != 4)
        return;
    var title = requestObject.responseText;
    alert(title);
}


Now let's open the connection:

var req = new XMLHttpRequest();
req.open('POST', '/getBookTitle.php', true);


'POST' means we're doing an HTTP POST operation (like a form being submitted) rather than using parameters in the URL. This is usually the best way to do things because often you'll want to send a lot of information to the server in order to get the exact information you require, and using the address parameters (the query string) isn't always a very good way to do it.

true refers to the fact that we'd like to do an asyncronous operation. If you specified false, when we actually send off the request, the browser would freeze at that point in the function and the next line would not execute until the call returned with the response from the server.

Let's Write Some Ajax Code (Part 3) 

Sending the data and some final words

Now that we've prepared the connection, we have to tell it what function to call when it's finished and then send off the data. The request object has a property called onreadystatechange. This is a reference to a function of your choice that will be called when the request object has some information it wants to let you know about. The function we defined above is what we'll use here. Also, we're going to assume that there's already some information in a variable containing the ISBN for the book. It is up to you to collect that information in whatever way is appropriate for your web page. For example, you might get it out of a text field on your html page.

var someISBN = '123456789';
req.onreadystatechange = ShowBookTitle;
req.send(someISBN);


There you have it. The concept is quite simple, but realistically you'll want a proper Ajax library which takes care of other stuff like reusing request objects, error handling and other relevant tasks. There are quite a few libraries out there. I'd recommend checking out the Ajaxian resources pages for some libraries you can use. Unless you have a good reason to reinvent the wheel, it's usually best to save time and leverage other peoples' hard work.

Reader Feedback 

Let me know what you think of the article!

submit

Great Stuff on Amazon 

Professional Ajax, 2nd Edition (Programmer to Programmer)

Amazon Price: $26.39 (as of 12/05/2009) Buy Now

Head First Ajax

Amazon Price: $29.69 (as of 12/05/2009) Buy Now

The Essential Guide to Dreamweaver CS4 with CSS, Ajax, and PHP (Essentials)

Amazon Price: $31.49 (as of 12/05/2009) Buy Now

Ajax: The Definitive Guide

Amazon Price: $31.49 (as of 12/05/2009) Buy Now

AJAX and PHP: Building Responsive Web Applications

Amazon Price: $27.75 (as of 12/05/2009) Buy Now

Building a Web Site with Ajax: Visual QuickProject Guide

Amazon Price: $13.59 (as of 12/05/2009) Buy Now

by snowdevil

Nathan Ridley is a designer, coder and aspiring entrepreneur. See here for more information.

(more)

Explore related pages

Create a Lens!