Techie Baba

Tuesday, November 14, 2006

AJAX : A New Approach to Web Applications

Ever wondered whats behind Google Maps, or Google Suggest, etc. Here I have tried to explain AJAX technology in simple words.

What is AJAX?

AJAX stands for Asynchronous JavaScript And XML. It is a technique used for communicating with the web server to send and retrieve data without loading a new page or reloading the current page.

To do this, the XMLHttpRequest object is used. This object is supported by most modern browsers in one form or another. As the name implies, the object allows you to perform HTTP requests which returns some form of response. The XML part refers to the fact that the object can automatically parse an XML document sent in response to a request.

HTTP Request: When you load a web page in your browser, say "http://www.example.com/index.html", the browser first opens a connection to the host, www.example.com. It then sends the server an HTTP request which consists of several lines of plain text. A typical request may look something like this:

GET /index.html HTTP/1.1

Host: www.example.net

User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.12)...

Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,...

Accept-Language: en-us,en;q=0.5

Accept-Encoding: gzip,deflate

Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7

Keep-Alive: 300

Proxy-Connection: keep-alive

Pragma: no-cache

Cache-Control: no-cache

HTTP Response: The first line contains the HTTP verb or method. In this case, the method is GET which means return the following document. Following that is the path to the document to retrieve (/index.html). The HTTP/1.1 tells the server what version of HTTP the browser supports.

The web server will return a response. Like the request, this consists of several lines of plain text. A typical response to the above request will look something like this:

HTTP/1.x 200 OK

Server: Microsoft-IIS/5.1

Date: Fri, 20 Jan 2006 19:29:47 GMT

Content-Length: 534

Content-Type: text/html

Cache-Control: private

<html >

<head>

<title>About Us</title>

</head>

<body>

<h1>About us</h1>

<p>...</p>

</body>

</html>

The first line contains the HTTP version and a three digit status code. The text following that number is a short description of that code. 200 means "OK," the request was successfully processed. If the requested page did not exist, the status would be "404 Not found."

The lines following are request headers. Like the response headers, these give additional information about the response such as the document type ("text/html") and size (534 bytes).

A blank line follows, signaling the end of the response header. The rest of the lines represent the response data. In this case, it is the HTML of the page which the browser will parse and render.

Passing Data in a HTTP Request:

There are two commonly used ways for a client to pass data in an HTTP request. One is to append a query string to the URL. For example,

http://www.example.com/signup.jsp?name=Shanky+Baba&email=shanky%40baba.com

The second way to pass data on an HTTP request is to use the "POST" method. This is often used with forms on web pages. An example of a POST request generated when a user submits a form is shown below:

POST /signup.jsp HTTP/1.1

Host: www.example.com

User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.12)...

Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,...

Accept-Language: en-us,en;q=0.5

Accept-Encoding: gzip,deflate

Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7

Keep-Alive: 300

Connection: keep-alive

Content-Type: application/x-www-form-urlencoded

Content-Length: 38

name=Shanky+Baba&email=shanky%40baba.com

The XMLHttpRequest Object:

With the XMLHttpRequest object, you can make HTTP requests from within JavaScript code on a web page and access the data returned by the web server.

XMLHttpRequest Object

Properties

readyState

A number representing the current state of the request:

0 - UNINITIALIZED

1 - LOADING

2 - LOADED

3 - INTERACTIVE

4 - COMPLETE

status

The numeric HTTP status code returned by the web server.

statusText

The text associated with the above HTTP status code. For example, 200 means "OK" and 404 means "Not found".

responseText

A string containing the response data returned from the web server.

responseXML

If the web server returns an XML document, this will be a DOM document object representing the parsed XML.

Methods

open(method, url, asynch, username, password)

Initializes a new request. method is the HTTP request verb, usually "GET" or "POST". The last three options are optional: asynch defaults to true, username and password may be specified if the web server requires authentication.

setRequestHeader(name, value)

Sets a named request header.

send(data)

Makes the request. optionally passing data.

abort()

Aborts an active request.

getResponseHeader(name)

Returns the value of the named response header.

getAllResponseHeaders()

Returns a string containg all the response headers.

Events

onreadystatechange

Raised anytime the readystate property changes.

Table 1 : XMLHttpRequest Object

Step 1: Create an XMLHttpRequest Object

The code below can be used to create an XMLHttpRequest object despite the browser differences.

// Define a list of Microsoft XML HTTP ProgIDs.

var XMLHTTPREQUEST_MS_PROGIDS = new Array(

"Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0",

"Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",

"Microsoft.XMLHTTP");

// Returns XMLHttpRequest object.

function getXMLHttpRequest() {

var httpRequest = null;

// Create the appropriate HttpRequest object for the browser.

if (window.XMLHttpRequest != null)

httpRequest = new window.XMLHttpRequest();

else if (window.ActiveXObject != null) {

// Probably browser is IE, find the right ActiveXObject.

var success = false;

for (var i = 0; i< XMLHTTPREQUEST_MS_PROGIDS.length && !success; i++) {

try {

httpRequest = new ActiveXObject(XMLHTTPREQUEST_MS_PROGIDS[i]);

success = true;

}

catch (ex) {}

}

}

// Display an error if we couldn't create one.

if (httpRequest == null)

alert("Error in HttpRequest():\n\n" + "Cannot create an XMLHttpRequest bject.");

// Return it.

return httpRequest;

}

We can then define an XMLHttpRequest object like so,

var myXmlHttpRequest = getXMLHttpRequest();

Step 2: Open a Request

Now we can open a connection to a specified URL using the code below:

myXmlHttpRequest.open("GET", url, true);

Two ways of Parameter Passing through AJAX:

  • Passing parameter through URL : example http://www.example.com/signup.jsp?name=Shanky

Here you access the variable called “name” in your server code and get the

value “Shanky”.

  • If you want to pass a larger amount of data to the request we can use POST method. To be able to do this we need to add a request header and pass data in the send() command. Example code:

myXmlHttpRequest.open("POST", url, true);
myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
myXmlHttpRequest.onreadystatechange = callbackFunctionName
var myform = document.forms[0];
var reqBody = getRequestBody(myform);
myXmlHttpRequest.send(reqBody);

Step 3: Create Response Handler

Since we made an asynchronous request to the server we don’t wait for the server to send the response. So we specify a callback function so that when server finishes its job it can notify the callback function of its response.

XMLHttpRequest object has a property called readyState that contains values depending upon the current status of the request. (Refer Table 1 for details.)

We have an associated event handler onreadystatechange using which we can specify a call back function when server processing is over and the readyState has a value of 4 (i.e. complete).

myXmlHttpRequest.onreadystatechange = callbackFunctionName

An example response handler function (a Javascript function):

function callbackFunctionName() {

if(myXmlHttpRequest.readyState == 4) {

if(myXmlHttpRequest.status == 200) {

//Write your action

Document.getElementById(‘id’).innerHTML =

myXmlHttpRequest.responseText;

} else {

alert(“Error: HTTP “ + myXmlHttpRequest.status + “ : “

+ myXmlHttpRequest.statusText);

} //end else

} // end if

} //end function

Step 4: Send the Request (or submit the request to server)

The last and final step to complete your AJAX application is to send the XMLHttpRequest object to the server.

myXmlHttpRequest.send(null);

or, myXmlHttpRequest.send(data);

where ‘data’ can be a piece of data to be send to the server as shown in sample code in Step 2, where we send the form data of html to the server.

Some Miscellaneous stuff:

Response Type: We can check the content type of the response in the response header. Normally the response that we are expecting to get back will be either an XML or a plain text. This can be checked by following code:

var cType = this.getResponseHeader("Content-Type");

if (cType == 'text/xml') {

// XML response
} else if (cType == 'text/plain') {

// plain TEXT response
} else {

alert('unknown content type');

}

Aborting A Request: Since AJAX is processed asynchronously, we can limit the request to just one request through some minor alteration in the code:

Replace

var myXmlHttpRequest = getXMLHttpRequest();

With this

if (!myXmlHttpRequest)

myXmlHttpRequest = createXMLHttp();
else if (myXmlHttpRequest.readyState != 0)

myXmlHttpRequest.abort();



This article has now moved to my new BLOG.

Labels: , , , , , , , , , , ,