Ajax Tutorial (original) (raw)

Asynchronous Javascript + XML Creating client-side dynamic Web pages

Ajax is only a name given to a set of tools that were previously existing. The main part is XMLHttpRequest, a server-side object usable in JavaScript, that was implemented into Internet Explorer since the 4.0 version.
XMLHttpRequest was developed by Mozilla from an ActiveX object named XMLHTTP and created by Microsoft.
The use of XMLHttpRequest in 2005 by Google, in Gmail and GoogleMaps has contributed to the success of this format. But this is the when the name Ajax was itself coined that the technology started to be so popular.

Summary

Why use Ajax?

But Ajax can selectively modify a part of a page displayed by the browser, and update it without the need to reload the whole document with all images, menus, etc...
For example, fields of forms, choices of user, may be processed and the result displayed immediately into the same page.

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

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:

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

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.

Building a request, step by step

First step: create an instance

This is just a classical instance of class, but two options must be tried, for browser compatibility.

if (window.XMLHttpRequest)     // Standard object { xhr = new XMLHttpRequest();     // Firefox, Safari, ... } else if (window.ActiveXObject)   // Internet Explorer { xhr = new ActiveXObject("Microsoft.XMLHTTP"); }

Or exceptions may be used instead:

try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); // Trying IE } catch(e) // Failed, use standard object { xhr = new XMLHttpRequest(); }

Second step: wait for the response

The response and further processing are included in a function and the return of the function will be assigned to the onreadystatechange attribute of the object previously created.

xhr.onreadystatechange = function() { // instructions to process the response };

if (xhr.readyState == 4) { // Received, OK } else { // Wait... }

Third step: make the request itself

Two methods of XMLHttpRequest are used:
- open: command GET or POST, URL of the document, true for asynchronous.
- send: with POST only, the data to send to the server.

The request below read a document on the server.

xhr.open('GET', 'https://www.xul.fr/somefile.xml', true);
xhr.send(null);

Examples

Get a text

 

Syntax of form using Ajax

Comments on the code:

new ActiveXObject(Microsoft.XMLHTTP)
This constructor is for Internet Explorer.

new XMLHttpRequest()
This constructor is for any other browser including Firefox.

http.onreadystatechange
An anonymous function is assigned to the event indicator.

http.readyState == 4
The 4 state means for the response is ready and sent by the server.

http.status == 200
This status means ok, otherwise some error code is returned, 404 for example.

http.open( "POST", "data.xml", true);
POST or GET
URL of the script to execute.
true for asynchronous (false for synchronous).

http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
This is for POST only.

http.send(document.getElementById("TYPEDTEXT").value);
Send data to the server. Data comes from the "TYPEDTEXT" variable filled throught the form by the user.

Get from XML

To get data from an XML file, we have just to replace this line:

document.ajax.dyn="Received:" + xhr.responseText;

by this code:

// Assign the XML file to a var var doc = xhr.responseXML; // Read the first element var element = doc.getElementsByTagName('root').item(0);    // Assign the content to the form document.ajax.dyn.value= element.firstChild.data;   

Write to body

The text read is put into the body of the page, and not into a textfield.
The code below replaces the textfield form object and the second part replaces the assignment into the JavaScript function.

 ... some text to replace ...

document.getElementById("zone").innerHTML = "Received:" + xhr.responseText;

Post a text

A text is sent to the server and is written into a file. The call to the "open" method changes, the argument is POST, the url is the name of a file or script that receives the data sent, and that must process it. And the "send" method has now a value as argument that is a string of parameters.

xhr.open("POST", "ajax-post-text.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);

The parameter of the send method is in the format of the HTML POST method. When several values are sent, they are separated by the ampersand symbol:

var data = "file=" + url + "&content=" + content;

The "file" parameter is the name of a file created to store the content. The filename must be checked by the server to prevent any other file to be modified.

The demonstration is included in the archive.

Using an external file

It is simpler to include a JavaScript file. This line will be included into the head section of the HTML page:

And the function is called with this statement:

var xhr = createXHR();

The script in the ajax.js file:

function createXHR() { var request = false; try { request = new ActiveXObject('Msxml2.XMLHTTP'); } catch (err2) { try { request = new ActiveXObject('Microsoft.XMLHTTP'); } catch (err3) { try { request = new XMLHttpRequest();} catch (err1) { request = false;} } } return request; }

How to build an Ajax website?

You need for some wrapper. A short list of frameworks is provided below.
Your JavaScript program, integrated into a web page, sends request to the server to load files for rebuilding of pages. The received documents are processed with DOM's methods or XML parsers and the data are used to update the pages.

Drawbacks of Ajax

- If JavaScript is not activated, Ajax can't works. The user must be asked to set JavaScript from within options of the browser, with the "noscript" tag.
- Since data to display are loaded dynamically, they are not part of the page, and are ignored by search engines and thus not indexed.
- The asynchronous mode may change the page with delays (when the processing on the server take some times), this may be disturbing especially since the result can happens after the instructions that call the server.
- The back button may be deactivated (this is not the case in examples provided here). This may be overcomed and it is easily with HTML 5.

Download

Specifications and references

Ajax is based on these specifications:

But was first described by this article:

Resources

More

Tools

Frameworks

Forum

© 2006-2022 Denis Sureau and xul.fr