AJAX is a buzzword these days. What really is AJAX ? Is it a new technology ? New framework ?
AJAX ( Asynchronous Javascript And XML ) is mainly used for manipulating the part of the web page and transfering some computation to the client system. Using this technology the page need not be reloaded when a part of the page changes because of user actions. This can be achieved by dynamically getting the data from the server when user interaction happens using the XMLHTTPRequest object. This is the new approach of developing rich client application.
AJAX is the mix of :
The traditional problem we have is, a lack of interactiveness for web applications like Desktop applications. When we submit a form or request some data from the server from the client side, the client has to wait till the request is processed and response is sent back to the client. If the server side request handler is taking long time to process the request, the client has to wait till the response comes back, probably with "working-in-background" mouse pointer or "Busy" mouse pointer. This is really annoying to the users and if user clicks many times on the windows that’s working on the request, OS may report that window as "Not Responding" and shows a blank white screen with just the title bar appearing (referring to IE on Windows). And users like me will definitely go to the taskbar and try to end the process. What if we can do this request processing work in the background asynchronously not disturbing the front-end screen and display a proper and relevant message "Processing Request" or "Waiting for reply" and allow the user to continue with some other tasks in the same window.
A Simple usecase:
In the web application I am working on has user selection field, which can be used to select any corporate user. (This is used to select users in a HTML form). Once the user selects "user selection" field and selects the particular corporate user, then the information regarding the selected user , like phone number, mailstop, mail address, manager, will be displayed in other fields of the form. The present solution developed waits till the request is processed and user can’t do any other task, like filling up other fields of the form in the same page. And sometimes, it takes nearly 30 seconds to 1 min for the response. If the user tries to click the window two or three times during this period then a blank window will appear and nothing works. And as I told you before, users like me will definitely kill the window using Task Manger and I have done that many times. This is a real annoying situation for the end user. This can be quite enough for a user to stop using the application altogether. So, what if we process that request of getting user information in the background asynchronously and still allowing the user to work on other fields of the form and process the information once we get the response from the back-end server ?
This kind of situations can be very well handled using AJAX, which has A ( Asynchronous ) at it’s core. Let’s get to the code and see how we can use AJAX in an application.
XMLHttpRequest Object:
One of the core component in AJAX framework is XMLHttpRequest object which allows asynchronous processing. XMLHttpRequest object also supports events. So, we can take actions whenever that’s necessary instead of continously checking for the status of the request. For example, we can just set a event handler to execute when the request is completed and response is received and continue with other tasks in the page and or wait for user input. This object also supports XML content. If the response is XML content then we can directly get a XML DOM object instead of taking the string and constructing the XML DOM object explicitly. Let’s look at the features of this object.
Object Methods (Most commonly used ):
open( method, URL, [isAsynchronous]) : This method is used to tell XMLHTTPRequest object which url to be considered to open the connection, what’s the method to use (GET/POST/PUT) and whether to process this request (accessing the specified URL) asynchronously or synchronously. The third parameter is option and by default it’s true, meaning that the request is processed asynchronously. The other optional parameters include username and password.
Example:
var xmlHttpRequest; //XMLHTTPRequest object
...... ( object construction goes here...will look into this later)
xmlHttpReuqest.open("GET","http://www.geocities.com/keelypavan/test.xml",true) // This method tells the object to get http://www.geocities.com/keelypavan/test.xml using GET method asynchronously. This is a dummy URL I used for demonstration purpose.
Note: This open doesn’t really open the connection to the server. We should call send(..) method for the request to be actually sent.
send( parameters as string ) : This method is used to actually send the request to the server for processing. Parameters if any specified will be sent to the server. Typically if the method id GET then the parameter will be null or an empty string or call the method without any parameters. If the method is POST then the parameter string would be the POST parameters in query string format, i.e. name=value pairs delimited by "&".
Example:
var xmlHttpRequest; //XMLHTTPRequest object
xmlHttpRequest.send( null ); //for GET
xmlHttpRequest.send( "name1=value1&name2=value2....");
Note: Make sure to set the onreadystatechange event handler before using the send method on the object.
abort():This Method aborts the request operation.
setRequestHeader( headerName, headerValue): Sets the request headers that will be sent to the server with the request.
Example:
var xmlHttpRequest; //XMLHTTPRequest object
xmlHttpRequest.setRequestHeader("IF-MODIFIED-SINCE","Sat, 04 Feb 2006 17:47:00 PST");
getResponseHeader( headerName ): Gets the specified response header sent by the server. Example response header are, content-type, content-length etc.
getAllResponseHeaders():Gets all the response header with header name and value as a string.
Properties:
readystate: Returns the ready state of the http request, which represents the internal state of the obejct. Values are listed below.
0 | Unintialized |
1 | Loading |
2 | Loaded |
3 | Interactive |
4 | Completed |
onreadystatechange: Sets the event handler function which will be called everytime there is a state change (readystate value change).This method is useful as we are requesting the resource from server asynchronously not waiting for the response. So, applications can use this method to come back and perform the necessary action when the request is completed.
status: Returns the status sent by the server. This status is HTTP status code. At the high level these codes mean:
1xx | Informational |
2xx | Successful |
3xx | Redirection |
4xx | Client Error |
5xx | Server Error |
statusText:Returns the text message (string) associated with the status code returned by the server.
For Example: Server send "OK" with the status code 200.
responseText: Returns the content of the response as a string returned by the server. Using this properly when the object is not is completed "readystate" will give an error.
reponseXML: Returns the XML DOM Document object if the response content is XML. For this to work, the server should send the XML content with content-type set as "text/xml" otherwise the responseXML will be empty. This is an important thing for developers as sometimes everything would be fine, the response will be XML content and XML will be well-formed but the responseXML method will not return DOM Document object.
If the response content is not well-formed XML, then the responseXML will return DOM Document with the parseError properly set so that applications can be aware of the problem.
Example:
Now let’s take an example and see how AJAX works.
Note: The sample application I developed works in IE, will try to develop a cross-browser app soon.
The sample application gets the RSS feeds from http://www.traffic.com/ site and displays them in the page.
The link to the application is: http://www.geocities.com/keelypavan/Ajax_traffic_update.html
Note: As this application tries to get the RSS feeds from traffic.com site, the security option allowing access to other domain resources should be enabled.
Object Creation:First let’s look at the object creation.
Object creation code:
if( window.XMLHttpRequest )
{
try{
xmlHTTPObj = new XMLHttpRequest();
}catch(e)
{
xmlHTTPObj = null;
}
}
else if( window.ActiveXObject )
{
try{
xmlHTTPObj = new ActiveXObject("MSXML2.XMLHTTP");
}catch( e )
{
xmlHTTPObj = null;
}
if( xmlHTTPObj == null )
{
try{
xmlHTTPObj = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e)
{
xmlHTTPObj = null;
}
}
}
This code uses the object detection technique to find out whether the object is defined in the browser environment. If yes, then this code creates that particular object and returns it. The other way of creating this object is using browser detection technique, meaning, check which browser is executing this piece of code and create the object accordingly. If it can't create the object, it would return a null value.
Sending Request:
Piece of code used for sending request:
document.getElementById("trafficDetails").innerHTML = "Loading Data ...";
var selectedCity = obj.options[ obj.selectedIndex ].value;
if( selectedCity != "" )
{
xmlhttp.open("GET",rssXMLBaseURL+trafficRSSXMLs.get( selectedCity ),true );
xmlhttp.setRequestHeader("If-Modified-Since","Thu, 26 Jan 2006 00:00:00 GMT");
xmlhttp.onreadystatechange = processRequest;
xmlhttp.send( "" );
}
else
{
document.getElementById("trafficDetails").innerHTML = "Select a city";
}
it uses, open(...), setRequestHeader(...), onreadystatechange, send() with the XMLHttpRequest object.
The first method used with XMLHttpRequest object is open(...). This method assigns the HTTP method to use to get the resource, URL and asynchronous flag.
setRequestHeader method is used in this case to check to see if the server resource has changed after the specified date and time. This has been set to a past date to get the content everytime.
onreadystatechange(..) method is used to set the event handler method.
At this point, the request is not yet sent but all other parameters are set. The next method send() transmits the HTTP request to the server. Be sure to set event handler method, onreadystatechange, before using send() method on the object.
Event Handler Method ( i.e. processRequest ): This method will be called every time there is a change in the readystate of the object. This method checks the readystate value and if it’s in completed state ( value 4 ) then it tries to see what’s the status code returned by the server. If status is 200 (successful) then it tries to get the content with responseXML and transforms using XSLT. You can get the XSLT source by clicking this link: http://www.geocities.com/keelypavan/trafficConditions.xsl. If the status code is not 200, then it reports an error string statusText.
The piece code is:
if( xmlhttp.readystate == 4 )
{
var divObj = document.getElementById("trafficDetails");
if( xmlhttp.status == 200 )
{
divObj.innerHTML = xmlhttp.responseXML.transformNode( xsltDoc );
}
else
{
divObj.innerHTML = "Could not load data";
alert( "Error:"+xmlhttp.statusText );
}
}
End of example:
Conclusion:
AJAX is very much useful to get the dynamic content from the server. This can be used to get the content of from the server even after the page load, in better terms, lazy loading and create very rich and interactive applications.
9 comments:
Very Good Article. Nice examples. Way 2 go Keely
Good article for beginners, great work!!!
The Intro to AJAX is good keep it up Pavan.
Hi Keely, We are using AJAX , facing some issues in accessing our application through VPN, but it works without using VPN. Please let me know how can I get more help on this.
Thanks. (vvishwa2000@yahoo.com)
Hi Viswa,
Can you please explain me what kind of problems you are experiencing using VPN.
Pavan Keely
naice artikle
@vish, the vpn problems can normally be solved by making sure all your server names are fully qualified -- that is put your domain name on your server so it resolves correctly. If your url is this:
http://myserver/myreport
change to this:
http://myserver.mydomain.com/myreport
HI,
The problems with VPN are resolved. The problem was with the timeout value specified in the code and it has got nothing to do with the server names. I took the problem offline and didn't update the blog comments.
Cheers...
Pavan Keely
Nicely written - simple and informative.
Daz
Post a Comment