Thursday, 16th June 2005
Added AJAX to improve my site
Two of the buzz words today in web development are AJAX and Ruby On Rails. Like everyone else, I was amazed when I saw some rich client applications like Google Maps and Google Suggest. I wondered how could you do that. Well, the secret is now out, AJAX !!! All of the major products Google has introduced over the last year - Orkut, Gmail, the latest beta version of Google Groups, Google Suggest, and Google Maps - are Ajax applications. (For more on the technical nuts and bolts of these Ajax implementations, check out these excellent analyses of Gmail, Google Suggest, and Google Maps.) Others are following suit: many of the features that people love in Flickr depend on Ajax, and Amazon's A9.com search engine applies similar techniques. AJAX can be used in conjunction with any server side scripting language not just Ruby On Rails although it is considered to be best option.
These projects demonstrate that Ajax is not only technically sound, but also practical for real-world applications. This isn't another technology that only works in a laboratory. And Ajax applications can be any size, from the very simple, single-function Google Suggest to the very complex and sophisticated Google Maps.
AJAX is the interactive web technology behind Google Maps and Google Suggest that's taking the web by storm. AJAX stands for Asynchronous Java and XML.
According to me AJAX makes surfing a lot easier especially if the viewer is on a slow internet connection, improves response time (critical for thin clients) and should ideally be incorporated in any well thought out application.
Javascript is one of my least favorite languages, but it's one of the few options for the active client part of the system. And as Google Maps has shown, there are some incredible things an AJAX architecture can do that server-side scripting can't.
The classic web application model works like this: Most user actions in the interface trigger an HTTP request back to a web server. The server does some processing - retrieving data, crunching numbers, talking to various legacy systems such as databases etc - and then returns an HTML page to the client. This approach makes a lot of technical sense, but it doesn't make for a great user experience. While the server is doing its thing, what's the user doing? That's right, waiting. And at every step in a task, the user waits some more. Obviously, if we were designing the Web from scratch for applications, we wouldn't make users wait around. Once an interface is loaded, why should the user interaction come to a halt every time the application needs something from the server? In fact, why should the user see the application go to the server at all?
AJAX is based on XMLHttpRequest. Although this concept isn't entirely new, XMLHttpRequest technology is implemented on more sites now than ever. Compatibility is no longer an issue (IE, Mozilla and Opera all support it), and the benefits to using it are amazing. Using the XMLHttpRequest object is not as hard as everybody thinks, and you don't need to buy and memorize another reference manual.
AJAX is a method of sending and receiving data (usually XML) from a server-side application through javascript. Since javascript offers the ability to change the contents of a web page on-the-fly, this technique allows web programmers to venture closer to programming truly interactive web applications similar to those built with Java and ActiveX.
XMLHttpRequest objects can be a simple way of getting data to and from a server side script (such as PHP,ASP,Perl etc) while keeping your client right at home on the same page. One simple example is an application that allows a user to select an option from selection box with several options. When a user selects an option, a request is sent to a server which returns a list of sub-options for the chosen option. The information can be used to generate a list of the results underneath the selection box. Since the information is not loaded with the initial page, bandwidth is saved, and because the user doesn't have to bounce from page to page for results, he will find your pages more inviting and faster to load.
Most websites have a fixed layout and structure. For example a banner at the top, navigation bar at top, bottom etc. All these remain fixed in almost all their webpages and the same HTML content is repeated in all the pages.
Consider my website for instance, all pages are based on the same template (all pages have the same fixed layout and only the central content varies from blog post to post). In such a case, blasting much the same HTML content for each web page is as much as waste of bandwidth as an increase in user response time. And considering that my audience likely includes folks from back home where broadband is not quite ubiquitous, the good UI feature to implement using AJAX is to have the layout HTML send to client browser only the first time that he visits my site while all furthur navigation using links uses AJAX to fetch the information (text) and display it in its placeholder.
Instead of loading a webpage, at the start of the session, Ajax engine allows the user's interaction with the application to happen asynchronously - independent of communication with the server. So the user is never staring at a blank browser window and an hourglass icon, waiting around for the server to do something.
Below i demonstrate how simple it is to use XMLhttpResponse. The XMLHttpRequest object works differently in Internet Explorer and Mozilla-like browsers.
Sending the request for information
function sendRequest() {
/* To create an XMLHttpRequest object in IE, the following can be used */
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
}
/* And the following works for supporting browsers other than IE */
else if (window.ActiveXObject) {
req=new ActiveXObject("Microsoft.XMLHTTP");
}
/* Since AJAX is asynchronous we need to provide a callback function to handle
the response when we recieve it */
req.onreadystatechange = processResponse;
/* URL of the server script which is going to send us back data.
In my case it is a PHP script, it could be anything */
var url = http://nikhilzkingdom.com/test-ajax.php
/* the third parameter indicates whether we want asynchronous processing or not, setting it to false makes the use of AJAX pointless !!! */
req.open("GET", url, true);
/* send the request */
req.send(null);
}
Recieving the response
/* When the server side script finishes execution, our req.onreadystatechange = processResponse callback function is called */
function processResponse()
{
/* The XMLHttpRequest object has a property called readyState with several states:
0: Uninitialized
1: Loading
2: Loaded
3: Interactive
4: Finished */
if (req.readyState == 4)
{
/ * the place holder div tag where the response data will be put in */
var obj = document.getElementById("center");
if (req.status == 200)
{
var response = http.responseText;
/* here we assume that the data recieved back is already HTML so directly assign it */
obj.innerHTML = response;
obj.focus();
}
else
{
obj.innerHTML = "Error";
}
}
}
Using POST instead of GET
/* if you wish to use a POST (especially useful to send large data) url instead of a GET url such as
http://my-host.com?arg1=val1&arg2=val2&arg3=val3.
*/
req.open('post',url);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send('arg1=val1&arg2=val2&arg3=val3');
Parsing XML Recieved
/* in the example above, i recieved plain text/html back from server script.
If you're receiving XML instead plain-text results from your processing server side script
you can use the javascript DOM to parse them.
To receive a DOM compatible response from our XMLHttpRequest object,
instead of using the responseText property, substitute the responseXML property.
If you want to avoid this, you could use the responseText method,
parsing the XML in PHP before sending it to the XMLHttpRequest object.*/
XMLRespone = req.responseXML;
/* This is a valid DOM3 object */
XMLReponse.getElementByTagName('tag_id');
To Sum up AJAX, use it to improve user feel of your website or webapplication. But be careful to overuse it or misuse it. And most important dont rely on it for the core functionality. Make sure that ur site/application works without it and no considerable dip in application usability since some users may disable java scripting in their browsers !!!. My advice is to build the site sans AJAX and then incorporate AJAX to improve web-usability.
Use AJAX to "fetch only what is needed and not everything".
Problems
Setting focus on the div tag which has the newly fetched data (using AJAX) doesnt still work perfectly on Firefox (suprisingly it does for IE).
For IE the following code works
obj = document.getElementByTagName("center");
obj.focus(); // works
But for Firefox, the focus doesnt work. Possibly in future releases, it will. If anyone knows a hack to this, i would appreciate if you would share it.
Using AJAX with PHP
My example above is extremely simple. For complex applications, it is best to use toolkits.
A couple AJAX toolkits for PHP are
SAJAX and JPSpan.
JPSpan provides a lot more functionality then SAJAX, the biggest difference you notice on the javascript side of thing is that you have mapped objects, on the php side the biggest difference is that you have a server page and a client page.
So thatz that with AJAX. It was great fun learning it. And with it, i was able to improve site respone time, save bandwidth and hopefully keep users happy.
Here is a test page to play around with AJAX.
Posted by Nikhil on Thursday, 16th June 2005 in TechnoBabble