The Anatomy of Ajax

Course- Javascript >

JavaScript is a client-side scripting language, and all of the examples you’ve used so far have been limited entirely to client-side coding. Ajax allows you to communicate with the server in the background and display the results on your page without having to carry out a page refresh. This lets you create pages that interact more smoothly with the user.

In this section, you’ll learn the basics of the technology that underpins Ajax, and how you can use jQuery to make the whole process slick and simple.

The Anatomy of Ajax

So far we’ve discussed only the traditional page-based model of a website user interface.

When you interact with such a website, individual pages containing text, images, data entry forms, and so forth are presented to you one at a time. Each page must be dealt with individually before navigating to the next.

For instance, you may complete the data entry fields of a form, editing and re-editing your entries as much as you want, knowing that the data will not be sent to the server until the form is finally submitted.

This interaction is summarized in below snapshot:

Traditional client–server interaction

After you submit a form or follow a navigation link, you then must wait while the browser screen refreshes to display the new or revised page that has been delivered by the server.

Unfortunately, interfaces built using this model have quite a few drawbacks. First, there is a significant delay while each new or revised page is loaded. This interrupts what we, as users, perceive as the “flow” of the application.

Furthermore, a whole page must be loaded on each occasion, even when most of its content is identical to that of the previous page. Items common to many pages on a website, such as header, footer, and navigation sections, can amount to a significant proportion of the data contained in the page.

This unnecessary download of data wastes bandwidth and further exacerbates the delay in loading each new page.

The combined effect of the issues just described is to offer a much inferior user experience compared to that provided by the vast majority of desktop applications. On the desktop, you expect the display contents of your programs to remain visible, and the interface elements to continue responding to your commands, while the computing processes occur quietly in the background.


Introducing Ajax

Ajax enables you to add to your web application interfaces some of this functionality more commonly seen in desktop applications. To achieve this, Ajax builds an extra “layer” of processing between the web page and the server.

This layer, often referred to as an Ajax Engine or Ajax Framework, intercepts requests from the user and in the background handles server communications quietly, unobtrusively, and asynchronously. This means that server requests and responses no longer need to coincide with particular user actions but may happen at any time convenient to the user and to the correct operation of the application. The browser does not freeze and await the completion by the server of the last request, but instead lets you carry on scrolling, clicking, and typing in the current page.

The updating of page elements to reflect the revised information received from the server is also looked after by Ajax, happening dynamically while the page continues to be used.

this snapshot represents how these interactions take place.

Ajax client-server interaction

The XMLHttpRequest Object

When you click on a hyperlink or submit an HTML form, you send an HTTP request to the server, which responds by serving to you a new or revised page. For your web application to work asynchronously, however, you must have a means to send HTTP requests to the server without an associated request to display a new page.

We can do so by means of the XMLHttpRequest object. This JavaScript object is capable of making a connection to the server and issuing an HTTP request without the necessity of an associated page load.

As a security measure, the XMLHttpRequest object can generally only make calls to URLs within the sandye domain as the calling page, and cannot directly call a remote server.

Different Rules for Different Browsers

Since you don’t know in advance which browser, version, or operating system your users have, you must have your code adapt its behavior on the fly to ensure that the instance of the object will be created successfully.

For the majority of browsers that support XMLHttpRequest as a native object (Firefox, Opera, and the rest, as well as later versions of Internet Explorer), creating an instance of this object is straightforward. The following line creates an XMLHttpRequest object called request:

var request = new XMLHttpRequest();

To achieve the equivalent result in some earlier versions of Microsoft Internet Explorer, you need to create an ActiveX object. Here’s an example:

var request = new ActiveXObject("Microsoft.XMLHTTP");

Once again, this assigns the name request to your new object.

To complicate matters a little more, some earlier versions of Internet Explorer have a different version of the Microsoft XML parser installed; in those cases you need to use the following instruction:

var request = new ActiveXObject("Msxml2.XMLHTTP");

Methods and Properties

Now that you have created an instance of your XMLHttpRequest object, let’s look at some of the object’s properties and methods, below given.

XMLHttpRequest Objects and Methods

Over the next few lessons we examine how these methods and properties are used to create the functions that form the building blocks of your Ajax applications.

Talking with the Server

In the traditional style of web page, when you issue a server request via a hyperlink or a form submission, the server accepts that request, carries out any server-side processing required, and subsequently serves to you a new page with content appropriate to the action you’ve taken.

While this processing takes place, your user interface is effectively frozen. You are made aware when the server has completed its task by the appearance in the browser of the new or revised page.

With asynchronous server requests, however, such communications occur in the background, and the completion of such a request does not necessarily coincide with a screen refresh or a new page being loaded. You must therefore make other arrangements to find out what progress the server has made in dealing with your request.

The XMLHttpRequest object possesses a convenient property to report on the progress of the server request. You can examine this property using JavaScript routines to determine the point at which the server has completed its task, and the results are available for you to use.

Your Ajax armory must therefore include a routine to monitor the status of your request and act accordingly. We look at this in more detail later in the section.

What Happens at the Server?

So far as the server-side script is concerned, the communication from your XMLHttpRequest object is just another HTTP request. Ajax applications care little about what languages or operating environments exist at the server; provided that the client-side Ajax layer receives a timely and correctly formatted HTTP response from the server, everything will work just fine.

Dealing with the Server Response

Once notified that an asynchronous request has been successfully completed, you may then use the information returned by the server.

Ajax allows for this information to be returned to you in a number of formats, including ASCII text and XML data.

Depending on the nature of the application, you may then translate, display, or otherwise process this information within your current page.

But There’s an Easier Way, Right?

Luckily, there are plenty of JavaScript libraries out there that make a good job of packaging these rather complicated procedures into easy-to-use functions and methods. In the remainder of this section you’ll see how the jQuery library can make writing Ajax scripts a piece of cake