Your Ad Here
Ajax

Bookmark and Share

Ajax and DHTML

Dynamic HTML has same purpose and is a set of standards:
- HTML,
- CSS,
- JavaScript.
DHTML allows to change the display of the page from user commands or from text typed by the user. Ajax allows also to send requests asynchronously and load data from the server. It is DHTML plus the XHR object.

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)     // Object of the current windows
{
    xhr = new XMLHttpRequest();     // Firefox, Safari, ...
}
else
 if (window.ActiveXObject)   // ActiveX version
 {
  // for Internet Explorer 
    xhr = new ActiveXObject("Microsoft.XMLHTTP"); 
 } 

Or exceptions may be used instead:

try {
   xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)    // Failed 
{
  xhr = new XMLHttpRequest();    // Other browsers.
}

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', 'http://www.xul.fr/somefile.xml', true);
xhr.send(null); 
Today's Deal