Ajax: What is it Good For?

Example Files

 

Note you will need to use either a local or remote server to view the example files. The example files can be downloaded from here:

 

Download Files

 

You can view the sliding interface template from the link below:

 

View Sliding Interface Template

 

The Ajax powered Fading Image Gallery can be viewed in action on this ‘buy video views’ page, please note you need to hover over the image to see it.

 

PDF File

 

A printable PDF file can also be downloaded from here:

 

Download PDF file

 

A Brief History

 

Many a year ago, Jeff Rouyer won the Netscape DHTML competition with his flying dude interface and put DHTML on the map. The winning entry, apart from being 3D in design which up until that point had not been seen on the Web, also had something that was quite uncharacteristic of Web pages.

Most of what you see today on the web in terms of DHTML Widgets can be attributed to a small number of people with Jeff leading the way. Granted there has been a progression over the years, but things like scrollers, tooltips, drag and drop, event handling, dynamic clipping etc were pioneered by Jeff many years before they became popular. For example, the sliding doors technique used in CSS today was used around ten years ago with JavaScript by Jeff. In short the guy is the grand daddy of DHTML and everyone else pales in comparison. I kid you not!

 

One of the unusual features of Jeff’s Award winning site was than rather than have a user traverse across multiple Web pages which consumes resources by opening separate window instances, Jeff was loading content dynamically into an existing interface. In other words all the content was being loaded into an existing element and all other elements were not being changed or swapped. We are talking pre Internet Explorer 4 days here. Here is a screen capture of that site.

 

Internet Explorer 4 was released a little later to challenge Netscape’s dominance on the web, but it did not have a similar method where content could be loaded directly into a layer element by using layer.load();

 

As the popularity of Internet Explorer 4 gained it became increasingly important to Jeff to maintain cross browser compatibility and initially created a series of document.write() in an external file to allow content to be imported into a pre-existing html file. Obviously this was resource intensive and he went on to improve this method for Internet Explorer 4 by created a little Java Applet to allow Internet Explorer 4 to pass external content into an existing element.

 

Not long after that, he thought of the idea of using an IFrame technique where content would be loaded into a hidden IFrame and then sucked back out and into a div element. This was the genesis of what today is known as Remote IFrame Scripting. Remember we are talking close to a decade ago which is a good indicator of how far ahead of the curve Jeff was at the time.

 

Around this time, Jeff and I struck up a friendship and began to work on refining that technique and over the years it progressed to what both Jeff and I currently use on our sites. We call it External HTML Loading.

 

As our friendship grew we started to think about writing a book. The whole problem with Jeff and I in this regard is that when we work together, we are too busy developing new things and rarely put pen to paper. In short we are too alike and enjoy the idea of creating new techniques as opposed to writing about existing techniques.

 

The interesting thing about working together in that manner was that we heavily were looking into using XML based techniques combined with existing HTML techniques. While we covered quite a bit of ground, the fact of the matter was that the only browser capable of using XML in any reasonable way was IE5+, so we tossed the idea out the window for the time being.

 

Enter Ajax

 

Recently Garret Smith of Adaptive Path made a good case for using Asynchronous JavaScript and XML and coined the acronym “AJAX” to represent that notion. It is similar to the Remote IFrame technique in that things are handled on the client side, but as we shall see differs in significant ways. That article reminded me of our earlier work on this front and sparked my interest in Ajax. Part of that interest is in writing this article and sharing my efforts with the development community.

 

To my way of thinking, Ajax is more a natural progression from an existing set of techniques as opposed to being something completely brand new. Yet within that progression, things are markedly different than in previous years in a couple of key areas:

 

 

    • It provides a mechanism to mix and match xml with xhtml.

 

    • It significantly reduces having to continually fetch things from a server (remote IFrame scripting is reasonably comparable here).

 

    • It overcomes some speed bottlenecks that traditional Web development has fallen prey too. In most instances an Ajax based site will load quicker than a comparable traditional Web site.

 

    • When done well, it significantly reduces initial load times.

 

 

Before proceeding, it should be noted that Ajax isn’t a panacea. It has some problems that it needs to overcome as it continues to mature. But it is a promising field to be involved within and as the years roll on, it probably will greatly affect the way we think about building Web pages and Web applications.

 

It also needs to be clear that Ajax isn’t a technology as such but rather is a technique that combines well with other technologies and techniques. For example, xml, dhtml, css, xhtml. In fact, Ajax really is DHTML with the xmlhttprequest object thrown in. It is amazing to think how one object can change the whole playing field.

 

As things currently stand in the Ajax field, we almost have two extremes going on. At one end of the continuum we have developers building all sorts of complicated JavaScript tags that in most instances are unnecessary and are overkill. At the other end of the scale we have these little examples floating around the Web that demonstrate how to load xml into a document or do some Ajax form processing.

 

While both ends of the spectrum have a part to play in the progression of the Web, I am not convinced that the principles of Ajax and how they can best be leveraged by a developer have been conveyed as well as they may have been.

 

This is particularly evident in the Ajax api’s that are available today. Most are appalling poor and suffer from code bloat. It is interesting to note that DHTML Api’s of the past suffer from the same problem. I was never an advocate for Api’s of this sort and see nothing that changes my mind in this regard.

 

What is Ajax?

 

Ajax itself is a technique, but to use the technique effectively one must become familiar with the philosophy behind the technique. In other words, it is not just the use of the technique that is important, but rather developing a different mindset and approach to Web development that is central.

 

To date, I have mentioned the term Ajax a number of times but have not described the central object that makes Ajax, Ajax. At the heart of Ajax are the xmlhttprequest object and its Microsoft’s activeX equivalent. It is this object that allows data to be transferred asynchronously. In case you are not clear what asynchronous means, it is the ability to handle processes independently from other processes. Synchronous which is the opposite of asynchronous, then means that processes are dependent upon other processes. To illustrate let us use a classical Web page scenario.

 

Assume we have page A and on this page we have a number of elements, including a couple of script and style tags. With synchronous data transfer the script tag needs to be parsed before the next element is parsed. In this way then the next element to be parsed by the browser is dependent upon the script tag being parsed first. Effectively we are creating a bottleneck of one connection between Web page and browser. Style tags and link elements in the head section of the document create the same bottleneck effect. They have to be parsed one at a time before other page elements can download.

 

Once they have been parsed then the elements in the body section can use concurrent connections to help speed up the download process. For example, most servers handle between 2 to 4 concurrent connections between web page and browser.

 

Consequently, this means that 2 to 4 images or other page elements can load concurrently. Yet before that process starts what is between the head tags have to be parsed first, which can considerably delay the loading of web pages. Most particularly if you are using multiple CSS and JavaScript tags. Nearly every Web page and blog on the internet uses this method. It isn’t hard to see why this may be a problem in terms of increasing page load speeds.

 

Asynchronously loading methods differ from this scenario because the loading processes are handled independently of each other and to a significant degree overcomes the bottle of traditional Web page design. As will be demonstrated later, the whole gist of this technique is to use minimal JavaScript initially and then push all the head related tags, including the rest of the JavaScript, CSS etc tags through an xmlhttprequest object. This method uses multiple connections rather than the single one that most traditional Web pages use and consequently speeds things up considerably. More on that later as we go through this tutorial.

 

In this tutorial I will be using xmlhttprequest to represent both versions: the xmlhttprequest object itself, (supported by, Firefox, Opera 8, Safari and later Mozilla builds and the Microsoft equivalent ActiveX object. I do this for the sake of brevity rather than anything else.

 

What to Expect

 

We are going to walk through the basics of Ajax and culminate in the building of a little Ajax powered Fading Image Gallery application. In this way it is hoped that a deeper appreciation for what Ajax is capable of is conveyed. It also should be noted that in another upcoming tutorial, we will tweak that Image Gallery widget and add some form processing capabilities to it, add some more FX, get a few glitches out of that system etc.

 

In other words, this initial tutorial is meant to help you get up and running in building your first Ajax powered Web application. Later we will look at refinement and adding features so that you can gain a more comprehensive understanding of the techniques and mindset required for Ajax. In short this tutorial is not meant to be the be all and end all of Ajax, rather it is better thought of as development in progress. Though the development in progress in this case has some clear aims and techniques to impart that should hopefully serve you well in future Ajax endeavours.

 

Just before getting into the code, techniques etc, I would just like to advise people that there is no need to attempt to cut and paste code from this tutorial. All files, which include both the image gallery application and a sliding book like interface, plus all examples are provided in a downloadable zip file. You will need to note, that the examples will not run offline unless run a server as a local host. At any rate, providing the examples as a downloadable file gives you a chance to play around with the files and suggest further improvements etc.

 

The two completed online examples that are provided are the Sliding Book Interface and the Ajax Fading Image Gallery.

 

Just in case you weren’t aware, the site you are now on also uses Ajax where lots of little components are being dynamically loaded as you interact with the web page. Bear that in mind as you read through this tutorial.

 

Having said all that, there is no better way than to dive into some code and walk you through it.

 

Onwards we go…

 

Basic XML Formatting

 

Let us begin by construct a basic xml file that will be loaded into the main document. Our xml example file (basic.xml) looks like this:

 

<?xml version=”1.0″ encoding=”UTF-8″?>

 

<menu>

 

<item>

 

<description>

 

Possible Menu Item Here

 

</description>

 

</item>

 

</menu>

 

Remember that XML doesn’t really do anything other than describe the content it contains. For example an xml tag such as the following:

 

<mynameis>

Eddie

</mynameis>

 

Allows the tags to describe what the content is. That is all the xml tags actually do.

 

In our basic XML example, we are eventually going to build a little navigation system therefore I used the tags, menu, items and description respectively to accurately represent what the tags contain.

 

Let us now turn our attention to the JavaScript that will allow us to load an xml file into an existing document. In case you are not clear, we are importing an XML Document into an existing HTML document. That is our immediate goal and forms much of the basis of what follows later on. It is worth paying attention to and going into some detail.

 

Ajax Manager Basic Script

 

Line 1: function ajaxManager()

{

Line 2: var args = ajaxManager.arguments;

Line 3: switch (args[0])

{

Line 4: case “load_page”:

Line 5: if (document.getElementById) {

Line 6: var x = (window.ActiveXObject) ? new ActiveXObject(“Microsoft.XMLHTTP”) : new XMLHttpRequest();

}

Line 7: if (x)

{

Line 8: x.onreadystatechange = function()

{

Line 9: if (x.readyState == 4 && x.status == 200)

{

Line 10: el = document.getElementById(args[2]);

 

Line 11: el.innerHTML = x.responseText;

}

}

Line 12: x.open(“GET”, args[1], true);

Line 13: x.send(null);

}

Line 14: break;

Line 15: case “start_up”:

Line 16: ajaxManager(‘load_page’, ‘basic.xml’, ‘contentLYR’);

Line 17: break;

}

}

 

As you may have noticed, I have numbered the JavaScript on a line by line basis. The best way to learn JavaScript is line by line, consequently it will be employed through this tutorial when apt.

 

Let’s Dig in to this script.

 

Line 1: This creates a new function which we call ajaxManager.

 

Line 2: we create a variable called args that points to all the arguments that the function will contain. We do this to cut down on file size rather that typing out ajaxManager.arguments on each occasion we want to make an argument. In case you do not know what a JavaScript argument is used for consider the following:

 

function alertMe(message){

alert(message);

}

 

In the alertMe function the argument employed is “message” and is contained within the parentheses. The argument itself is passed to a stock standard alert() method.

 

To generate an argument to represent the message we can do this on the body onload event.

 

<body onload=”alertMe(‘my name is Eddie’)”>

 

What this does is then pass ‘my name is eddie’ to the argument message and when the alert is triggered then my name is eddie is displayed in the alert dialogue. An argument is a system where you can pass information from an event to the function itself, which is particularly useful when working with programming languages.

 

Line 3: The function uses a case / switch methodology. Often rather than having a series of if / else statements we can use a case switch method with the same result with much less code and consequently more efficient processing of the script. A basic format for case switching is as follows.

 

switch (expression) {

case label1:

// Code to be executed

break;

case label2:

// Code to be executed

break;

}

 

In our code the expression is signified by an argument so that later we can use the labels of each case and call them from an event handler. By way of example,

 

onmousedown=”functionNameHere (‘caselabelhere’)”

 

or

 

ajaxManager(‘start_up’)

 

would signify to the browser to use the function ajaxManager and to only execute the start_up case. In using the case / switch method in this manner we are effectively creating sub functions within the main function that often results in code brevity.

 

Line 4: Creates our first case. In this instance we are creating a case labelled load_page.

 

Line 5: We don’t want older browser to use the script so we create an if condition to allow only browsers that support document.getElementById

 

Line 6: Now we are getting into the guts of the function. To use XMLHttpRequest with Internet Explorer 5 we need to use an Active X object where as Mozilla based browsers, Opera and Safari support XMLHttpRequest directly. So we have to create a little conditional switch to ensure that the right method is used for the right browsers. We do this by fist creating a variable named x and checking for the existence of an ActiveX object using a conditional operator. If an activeX object is found then the statement uses the method for IE if not it skips over to using XMLHttpRequest that is used by the other modern browsers.

 

For Internet Explorer, if we wanted to, we could use try and catch JavaScript methods to create some conditional branches to implement version dependent instances of XMLHTTP. For example Msxml2.XMLHTTP.3.0. In the next tutorial, we will implement these methods because they also are useful for error catching.

 

Using independent version conditions makes sense if you want to use a specific feature you know is supported by a particular version of XMLHTTP. In this instance however that isn’t applicable so we can use the version independent method which is Microsoft.XMLHTTP. That will work on IE5 through to IE7. It also has the added benefit of keeping our code nice and lean. And we like lean code don’t we!

 

Line 7: We check that either the Microsoft.XMLHTTP or XMLHttpRequest objects have been created through the usage of the previously named variable x.

 

Line 8: The onreadystatechange event is used to keep track of when the readystate of a document changes. In this statement we attach the event to Microsoft.XMLHTTP or XMLHttpRequest respectively by using the variable x.

 

We then create a function to handle all the processing that will follow. This is particularly useful to monitor the parsing and loading process of documents. The following readystates are available to developers.

 

0

uninitialized Object is not initialized with data.

1

Loading Object is loading its data.

2

loaded Object has finished loading its data.

3

interactive User can interact with the object even though it is not fully loaded.

4

complete Object is completely initialized.

 

Line 9: We have another conditional statement to check if the readystate = 4 has been triggered; which means that the document loading is complete and ready to be used and also check that the status of the document is completed by asking whether status = 200. If this check is ok then the following statements are triggered.

 

Line 10: We want to create a JavaScript object to load the xml file into. We could just load into the document.body, but using a container is far more flexible as you can then position imported xml data anywhere you like. To this end we create a variable named el and point it to the document.getElementById(args[2]) statement. The argument in the statement will allow us to later specify which element we want to load the data into. We could have just used document.getElementById(‘contentLYR’) where contentLYR would be a block element in the document body (usually a div tag) with an id value of contentLYR. And that would be perfectly acceptable in a lot of instances. However later on we are going to do some multiple data loading into different containers in the document so we want as much flexibility as possible.

 

Line 11: The next thing we want to do is actually place the data into an element. I find using innerHTML efficient in handling this task so let us use that method. Basically this line tells the browser to place the data into an element and display it.

 

Line 12: We want to open a request and obtain the data so this method allows for that. It uses three arguments Get, args[1] and true. Get as the term implies retrieves the data, the second argument args[1] will allow us to specify which data file to obtain and the third tells the browser to load the data asynchronously. If this third argument is set to true the data loads asynchronously and if set to false it does not.

 

The following table lists common XMLHttpRequest object methods:

 

Method

Description

abort() Stops the current request
getAllResponseHeaders() Returns complete set of headers (labels and values) as a string
getResponseHeader(“headerLabel”) Returns the string value of a single header label
open(“method”, “URL”[, asyncFlag[, “userName”[, “password”]]]) Assigns destination URL, method, and otheroptional attributes of a pending request
send(content) Transmits the request, optionally with postable string or DOM object data
setRequestHeader(“label”, “value”) Assigns a label/value pair to the header to be sent with a request

 

Line 13: If we wanted to transmit some data to and from a server we would specify the data to be transmitted. But since we don’t want to send data we set the send argument to null

 

Line 14: A break statement closes the case.

 

That is the core of an xml asynchronous loading technique. And it is well worth the effort to get to know it intimately. If you don’t understand it, try reading it again until you do. The next case is used to signify what is going to happen when the document loads.

 

Line 15: Creates a new case called start_up.

 

Line 16: This statement tells the browser what to do when the original document (not the document being loaded into the interface what to do. Here we specify that the ajaxManager function should be called, then to use the case load page, then to retrieve the xml file named basic.xml and to put it into a div tag called contentLYR.

 

Line 17: A break statement to close the case.

 

That’s it for the JavaScript section. It’s a pretty lightweight script that is capable of quite a few things that will be demonstrated later on.

 

Let’s now turn our attention to the original document where the xml data will be loaded into. It’s a pretty simple set up. All we need to do is insert a div tag with an id attribute and property of contentLYR like so;

 

<div id=”contentLYR”>

</div>

 

Then in a style sheet give it some properties and values. This is what I have used for this example:

 

<style type=”text/css”>

#contentLYR {

position:absolute;

width:200px;

height:115px;

z-index:1;

left: 200px;

top: 200px;

}

</style>

 

Nothing out of the ordinary there. You will just need some familiarity with CSS to arrange layout and presentation. There are a bunch of good CSS tutorials on the Web if you find yourself in unfamiliar territory.

 

Finally we call the ajaxManager and specify which case to employ from the body tag using an onload event like so:

 

<body onload=”ajaxManager(‘start_up’)”>

 

Let’s take a look at how this handles by viewing the example:

 

View Basic Example

 

As you can see the function does what it intends to do, but it doesn’t really highlight the versatility of XMLHttpRequest. Let’s go with a few different examples to demonstrate. Part 2 of this tutorial can be accessed by scrolling to the top of the page.

Leave a Reply

Your email address will not be published. Required fields are marked *