How does Ajax Work

Ajax is a term coined by Jesse James Garrett and that became popular since the publication of the article Ajax: A New Approach to Web applications, published on February 2005, is a shortcut for: Asynchronous JavaScript and XML.

The normal behavior of Internet that involves sending pages to the browser is completely changed by the use of Ajax.

Ajax has become commonplace with its integration in HTML 5 and JavaScript frameworks, and in fact, the interest of developers has moved to HTML 5 for its new tags and APIs that accompany it. Among these, WebSocket appears as the successor to Ajax, because it is a superior means of communication between an application and the server or the backend.

What's Ajax?

Ajax is a set of technologies, supported by a web browser, including these elements:

  • HTML for the interface.
  • CSS for the look and feel.
  • JavaScript (ECMAScript) for local processing, and DOM (Document Object Model) to access data inside the page or to access elements of XML file read on the server.
  • The XMLHttpRequest object is used to read or send data on the server asynchronously.
  • PHP or another scripting language may be used on the server.

The "asynchronous" word, means that the response of the server while be processed when available, without to wait and to freeze the display of the page.

Dynamic HTML has same purpose and is a set of standards: HTML, CSS, JavaScript. This allows to change the display of the page from user commands or from text typed by the user.

Ajax is DHTML plus the XHR object to exchange data with the server.

How does it Works?

To get data on the server, XMLHttpRequest provides two methods:

  • open: create a connection.
  • send: send a request to the server.

Data furnished by the server will be found in the attributes of the XMLHttpRequest object:

  • responseXml for an XML file
  • responseText for a plain text.

We have to wait for the data to be available to process it, and in this purpose, the state of availability of data is given by the readyState attribute of XMLHttpRequest.

States of readyState follow (only the last one is really useful):

  • 0: not initialized.
  • 1: connection established.
  • 2: request received.
  • 3: answer in process.
  • 4: finished.

The XMLHttpRequest object

Allows to interact with the servers, thanks to its methods and attributes.

Attributes
readyState
the code successively changes value from 0 to 4 that means for "ready".
status
200 is OK
404 if the page is not found.
responseText
holds loaded data as a string of characters.
responseXml
holds an XML loaded file, DOM's method allows to extract data.
onreadystatechange
property that takes a function as value that is invoked when the readystatechange event is dispatched.
Methods
open(mode, url, boolean)
mode: type of request, GET or POST
url: the location of the file, with a path.
boolean: true (asynchronous) / false (synchronous).
optionally, a login and a password may be added to arguments.
send("string")
null for a GET command.

How to Use it?

Ajax is used by defining JavaScript functions to use the XMLHttpRequest objects' methods and attributes, or simply by installing a framework that defines the most common tasks.

These frameworks include a JavaScript code that runs client side and possibly also code in another programming language that runs server side.

The role of the XHR object is to send requests to the server with the send function. The HTTP methods GET and POST as well as others, determine the nature of the request: GET to receive data, POST to send (and receive the result). The HEAD method gives information on the nature of a file on the server. The XHR object can receive text files, assigned to the responseText attribute, or XML assigned to responseXML.

Manually Using JavaScript

Create XMLHttpRequest
if (window.XMLHttpRequest) { 
    // Chrome, Firefox, Safari, ...
    xhr = new XMLHttpRequest();
}  else if (window.ActiveXObject) {
    // Internet Explorer 
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
Wait for Response
xhr.onreadystatechange  = function() { 
    if(xhr.readyState == 4) {
        if(xhr.status  == 200) {
            document.ajax.dyn="Received:"  + xhr.responseText; 
        } else {
            document.ajax.dyn="Error code " + xhr.status;
        }
};
Make the Request
xhr.open(POST, '/login.do',  true); 
xhr.send('username=someone&password=passwd');

Use Framework

One can use a JavaScript framework integrating Ajax, which enables to get data from the server sending data to a script more easily.

  • jQuery is a pure JavaScript framework, it adds widgets and special effects. It is distributed in separate code files which are included if needed, that preserves the lightness of the page.
  • Rico proposes to create rich Internet applications with drag and drop and a library of functions such as kinematic expansion, fading. The LiveGrid function connects an HTML table to a data stream from the server.
  • Mootools is another popular Ajax framework.

The trend is to HTML 5 frameworks providing lots of function to make an app, and including Ajax. They works often on mobiles and on the desktop.

Evolution of Ajax

Should the word Ajax be restricted solely to the definition that was given by JJ Garrett in 2005 or can we use the term about new technologies intended to create dynamic web pages?

In fact, from the outset, the definition was too restrictive because XML is far from being the single or preferential format to exchange data with a server.

However there are quantities of technologies to achieve modern web applications which must be distinguished from Ajax.

Therefore it is better to be clear to involve only the word to use XMLHttpRequest in combination with the technologies for dynamic pages listed above, and with any data format for the exchange with the server.

We can consider that Ajax in the future will designate any mode of asynchronous communication and updating dynamic pages, even if it is based on a different object replacing XHR, but this object must work on all browsers because Ajax is founded in principle on standards.

Ajax is actually surpassed technologically by new protocols as WebSocket which enables bidirectional communication (the server can send data itself) and WebRTC that goes further by providing real-time communication. But that does not mean that Ajax is useless in practice: very often it is more than enough to improve the user experience of an online application that depends on user actions.

A comparison of XMLHttpRequest and WebSocket is given in an article which explains how to use the XHR object and WebSocket, and the advantage of bidirectional exchanges over simple asynchronous protocol.

Contact Us
  • SenseTime Research, Shenzhen Bay Eco-Technology Park
  • cshzxie [at] gmail [dot] com