Monday, March 29, 2010

Ajax - Internal

Objective of this post is to expose behind the scene story of Ajax but lets start with classical definition of Ajax ...

1. What is Ajax?
Ajax is a web technology by which web client (web page) can interact with server asynchronously. Ajax stands for Asynchronous Javascript and XML. The whole story is around an object XMLHttpRequest which is an implementation, available in most browsers, of an interface XMLHttpRequest provided by scripting engine. IE has a different name of this object called XMLHTTP and instantiated as an activeX object. This object can be used by scripts to programmatically connect to their originating server via HTTP synchronously and asynchronously. Its asynchronous capability is exploited by AJAX for interactive communication with server.

2. Example
function ajaxCall(url) {
var req;

try {
req = new XMLHttpRequest();
} catch(e) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP"); // IE 6.0+
} catch(e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP"); // Older IE
} catch(e) {
throw new Error("Your browser doesn't support AJAX => " + e); // Doesn't support AJAX

req.onreadystatechange = function() {
if(this.readyState == 4) {
var data = req.responseText;
document.getElementById('response').innerHTML = data; // create a div with id 'response'
// $("#response").html(data); // if using jquery
};"GET", url, true);

Working with GET
Parameters can be passed as part of URL with GET e.g.

Working with POST (sending JSON object, sending DOM)
With POST send() method can have a Document, DOM string, JSON string or any simple text string.

◆ A new instance of XMLHttpRequest object needs to be created for each new request. This is so because once readyState gets changed it is not reset to 0.
◆ Some browsers don't implement no argument send() method. So it would be better to pass 'null' if there is nothing to pass.

3. XMLHttpRequest Explained

XMLHttpRequest has the following methods

abort()Aborts the current request
getAllResponseHeaders()Returns all of the HTTP headers as a string
getResponseHeader( headerName )Returns the specific value of the given HTTP header.
open( method, URL, async, userName, password )Opens a connection to the given URL using the given Method.
URL - The URL that you wish to connect to.
method - The HTTP method of which you wish to communicate by.
Possible Methods:
  • GET - most common
  • POST
  • HEAD
  • PUT
  • DELETE - least common
async - whether or not the connection should be asynchronous. For Ajax this is always true.
userName - username IF login is required
password - password IF login is required
send( content )Sends the request to the url in the open function. Content is any information that you wish to send to the server. This is typically null but depends on the method specified in the open function.
setRequestHeader( key, value )Adds a key-value pair to the HTTP header to be sent.

XMLHttpRequest has the following properties

onreadystatechangeA reference to an event handler for an event that triggers everytime the object changes state.
readyStateReturns the state of the object as follows:
  • 0 = uninitialized
  • 1 = open
  • 2 = sent
  • 3 = receiving
  • 4 = ready
responseTextThe response from the server contained in a single string.
responseXMLThe response from the server in XML format.
statusThe HTTP status code as a number
statusTextThe HTTP status as a string, ex: "Not Okay" or "Ok"

4. Interface of XMLHttpRequest object

XMLHttpRequest object is the implementation of interface provided by scripting engine as specified by W3C. Below is the interface

interface XMLHttpRequestEventTarget : EventTarget {
// for future use

interface XMLHttpRequest : XMLHttpRequestEventTarget {
// event handler attributes
attribute Function onreadystatechange;

// states
const unsigned short UNSENT = 0;
const unsigned short OPENED = 1;
const unsigned short HEADERS_RECEIVED = 2;
const unsigned short LOADING = 3;
const unsigned short DONE = 4;
readonly attribute unsigned short readyState;

// request
void open(DOMString method, DOMString url);
void open(DOMString method, DOMString url, boolean async);
void open(DOMString method, DOMString url, boolean async, DOMString? user);
void open(DOMString method, DOMString url, boolean async, DOMString? user, DOMString? password);
void setRequestHeader(DOMString header, DOMString value);
void send();
void send(Document data);
void send([AllowAny] DOMString? data);
void abort();

// response
readonly attribute unsigned short status;
readonly attribute DOMString statusText;
DOMString getResponseHeader(DOMString header);
DOMString getAllResponseHeaders();
readonly attribute DOMString responseText;
readonly attribute Document responseXML;

More information is provided by the W3C at