Wednesday, March 14, 2007

Ajax!

Asynchronous Javascript and XML, urf Ajax, was born from the frustration of -Waiting!

When you're viewing a page on your favourite site, and then you decide to login what happens? You enter your username and password, click 'Login', and then.... Wait. You need to wait for the page to reload, which means you are actually waiting for the client-server-client roundtrip to happen.

With Ajax, effectively, this request-response part keeps happening in the background while you can keep browsing, that is, no page reload issues!

This achieves better user interactivity, and gives you a rich client experience by bridging the gap between a Desktop App (Fancy UI experience) and a Web App (a more basic UI).

This magic is performed using a Javascript Object called XMLHttpRequest. You need to create a reference to this object, and use it to send your request to the server. You also use this referance to specify a handler method that renders the response whenever it arrives.
To render the response you mostly will be playing around with the DOM of the Page.
As the figure shows, the XMLHTTPRequest Object is what intervenes in the normal request-response cycle.
Creating a reference of this object is browser specific and here is a simple code that does it.

function newXMLHTTPReq()
{

var obj = false;

try //assuming a microsoft browzer that supports MSXML2 parser
{
obj = new ActiveXObject("Msxml2.XMLHTTP");

}
catch (e)
{
try //assuming a microsoft browzer
{
obj = false;
obj = new ActiveXObject("Microsoft.XMLHTTP");

}
catch (e1)
{
try
{
obj = false;
obj = new XMLHttpRequest();

}
catch (e2)
{
obj= false;
}
}
}

return obj;

}

As show, the try-catch exception mechanism is used here to achieve browser compatibility.
This is not the only way to create a browser specific reference, but i have chosen it for no real reason! It is possible to detect the browser being used, and fend for it,through Javascript.

Next, is to use this reference to create a connection with the server,and send it some data.


Shown above is the 'open' method call, which creates the connection. It has 3 parameters:
  1. The Method - GET / POST
  2. The URL of the backend entity that recieves and processes the request.
  3. A boolean value, which is the KEY to asynchronous request making - if TRUE, it is an asynch request that goes to the server and if false, then it behaves like a regular request-response cycle that keeps you waiting for the page to reload!
Here is a snippet that makes the request and handles the response. It uses the method above for creating a reference of type XMLHTTPRequest.

function getContent()
{
var req = newXMLHTTPReq();
req.onreadystatechange = function requestHandler()
{
if(req.readyState == 4) //When response is loaded
{
if(req.status == 200)
{
document.getElementById("sResults").value = req.responseText;
}
}
};

var pageURLString = document.getElementById("pURL").value;
var searchString = document.getElementById("sString").value;
var sendData = "pageURL="+pageURLString+"&searchString="+searchString;

req.open("POST","searchContentServlet",true); //Open connection to servlet
req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
req.send(sendData);
}



The Code in blue is what creates the connection and sends the data. Within this, the first 3 lines is what extracts the data from the HTML page and creates a DataString to send to the server. This datastring (like most query strings) must be of the form "parameter1=value1¶meter2=value2" that is, multiple parameters, separated by the ampersand sign.

The next three lines in blue is what sends the created string.

The entities in red are important. The req.onreadystatechange points to a handler. This handler is what is being repeatedly called behind the scenes. In this handler, two checks are performed which involve our other two Red Entities! :)

If req.readyState is 4, that means the loading of the response is Complete. Other ready states are as follows:
0 = uninitialized
1 = loading
2 = loaded
3 = interactive

If req.status is 200, that means the server responded successfully. 200 is a status code of success returned by the server, just like our very notorious 404 error is a 'resource not found' code returned by the server. Here is an explanation of more such codes.

This now means we have successfully received a response. Response in Ajax is mainly of two types - responseText which can be a String, JSON string (Blog post dedicated to JSON is in the pipeline :), fortunately or unfortunately ;-) ) and responseXML which one needs to parse using Javascript.

I have used responseText here (i chose to return a string from my servlet and not XML).

And this, i have displayed in a Textbox, as the green LOC shows.


This post has already become long and probably boring ;-) so i have covered just the starters of Ajax.

Ajax is good, has may people chasing it, and simple to use, but one can't use it for all types of applications most importantly transactional ones. Also, since after receiving the response one displays it by playing with the DOM of the page, using the back button in the browser has results different from what one expects.



4 comments:

Saurabh said...

Hey,
Good post.

Very smart companies like google etc, spend a lot of time and effort coding so that users get the same actions performed when they hit the back button.
A lot of code behind achieves this - but it is also pretty tricky to implement.

Also, the code snippets that you have shown, are the "raw" way to write AJAX.
Nowadays, two AJAX frameworks are extremely popular - which make writing AJAX enabled websites as simple as referencing a dll and using its function calls.

There is a free framework for PHP called Ruby on Rails (RoR) and you can download it from: http://www.rubyonrails.org/

The other one is for ASP.Net and is called Asp.Net Ajax (earlier atlas)
Download from: http://ajax.asp.net/

- Saurabh

Shalini said...

Hey,
Good inputs.

I decided not to write about frameworks to let it remain a beginners article. :)

Have been using a couple of Javascript Libraries myself.

One is prototype (http://www.prototypejs.org/) and the other is script.aculo.us (http://script.aculo.us/) which i think uses prototype, but im not sure.

Also, there is an overwhelming number of frameworks for java, most of which claim that the back-end can be anything from a plian servlet to struts.

Couple that i've looked into but never used, are AjaxAnywhere (http://ajaxanywhere.sourceforge.net/) and AjaxTags (http://ajaxtags.sourceforge.net/)

Jomy said...

Ok !

So , if you use the framework that you and jainy spoke of ...can you avoid the code that you just wrote ?

Also , does AJAX carry its own documentation or do J2EE/.NET contain it ?

Interesting stuff ! All i knew till date about AJAX was that google used it !

Im already waiting for your next post !

Shalini said...

Jammy,

Yes. If you use a framework, you can avoid the code i have posted :) It then just becomes a simple method call.

Second question hazy. But Ajax does carry a good amount of its own documentation online :)
If you want it specific to your platform then you google accordingly. Like 'j2ee+ajax' would give you many good hits.

And the open source community, who are never lagging at any point about anything, are sure to have taken care of specific needs,Apache Projects being one that i know of.