Monday 26 November 2012

Advanced Java Programming -- Introduction to AJAX


Advanced Java Programming -- Introduction to AJAX
Structure
9.1 Introduction
Objectives
Self Assessment Questions
9.2 Defining Ajax
9.3 How Does Ajax Work?
9.4 Summary
9.5 Terminal Questions
9.1 Introduction
The term Ajax is used to describe a set of technologies that allow browsers to provide users with a more natural browsing experience. Before Ajax, Web sites forced their users into the submit/wait/redisplay paradigm, where the users' actions were always synchronized with the server's "think time." Ajax provides the ability to communicate with the server asynchronously, thereby freeing the user experience from the request/response cycle. With Ajax, when a user clicks a button, you can use JavaScript and DHTML to immediately update the UI, and spawn an asynchronous request to the server to perform an update or query a database. When the request returns, you can then use JavaScript and CSS to update your UI accordingly without refreshing the entire page. Most importantly, users don't even know your code is communicating with the server: the Web site feels like it's instantly responding.
While the infrastructure needed by Ajax has been available for a while, it is only recently that the true power of asynchronous requests has been leveraged. The ability to have an extremely responsive Web site is exciting as it finally allows developers and designers to create "desktop-like" usability with the standard HTML/CSS/JavaScript stack.
Advanced Java Programming Unit 9
Sikkim Manipal University Page No. 241
Traditionally in J2EE, developers have been so focused on developing the service and persistence layers that the usability of the user interface has lagged behind. It is common to hear phases such as, "we don't have time to invest in the UI" or "you can't do that with HTML" during a typical J2EE development cycle. The following Web sites prove that these excuses don't hold water any longer:
 BackPack
 Google Suggest
 Google Maps
 PalmSphere
All these Web sites show that Web applications don't need to rely solely on pages being reloaded from the server to present changes to the user. Everything seems to happen almost instantly. In short, when it comes to designing a responsive user interface, the bar has now been set much higher.
Objectives
In this chapter, you will learn about the:-
 Definition of AJAX
 How does AJAX works.
Self Assessment Questions
1. What do you mean by AJAX ?
9.2 Defining Ajax
Jesse James Garrett at Adaptive Path defined Ajax as follows:
Ajax isn't a technology. It's really several technologies, each flourishing in its own right, coming together in powerful new ways. Ajax incorporates:
 Standards-based presentation using XHTML and CSS
 Dynamic display and interaction using the Document Object Model
Advanced Java Programming Unit 9
Sikkim Manipal University Page No. 242
 Asynchronous server communication using XMLHttpRequest
 JavaScript binding everything together
This is all fine and dandy, but why the name Ajax? Well, the term Ajax was coined by Jesse James Garrett, and as he puts it, it is "short-hand for Asynchronous JavaScript + XML."
9.3 How Does Ajax Work?
The kernel of Ajax is the XmlHttpRequest JavaScript object. This JavaScript object was originally introduced in Internet Explorer 5, and it is the enabling technology that allows asynchronous requests. In short, XmlHttpRequest lets you use JavaScript to make a request to the server and process the response without blocking the user.
By performing screen updates on the client, you have a great amount of flexibility when it comes to creating your Web site. Here are some ideas for what you can accomplish with Ajax:
1. Dynamically update the totals on your shopping cart without forcing the user to click Update and wait for the server to resend the entire page.
2. Increase site performance by reducing the amount of data downloaded from the server. For example, on Amazon's shopping cart page, when I update the quantity of an item in my basket, the entire page is reloaded, which forces 32K of data to be downloaded. If you use Ajax to calculate the new total, the server can respond with just the new total value, thereby reducing the required bandwidth 100 fold.
3. Eliminate page refreshes every time there is user input. For example, if the user clicks Next on a paginated list, Ajax allows you to just refresh the list with the server data, instead of redrawing the entire page.
4. Edit table data directly in place, without requiring the user to navigate to a new page to edit the data. With Ajax, when the user clicks Edit, you
Advanced Java Programming Unit 9
Sikkim Manipal University Page No. 243
can redraw the static table into a table with editable contents. Once the user clicks Done, you can spawn an Ajax request to update the server, and redraw the table to have static, display-only data.
The possibilities are endless! Hopefully you are excited to get started developing your own Ajax-based site. Before we start, however, let's review an existing Web site that follows the old paradigm of submit/wait/redisplay and discuss how Ajax can improve the user's experience.
Example of Where Ajax Could Be Used: MSN Money
I was on the MSN Money page the other day, and it had an article about real estate investing I found intriguing. I decided to use the "Rate this article" feature of the site such that other users of the site might be encouraged to invest their time in reading the article. After I clicked the vote button and waited a second, the entire page refreshed and I was presented with a beautiful thank you where the original voting question was.
Figure 9.3.1: Thank you message
Ajax could have made the user experience more pleasant by providing a more responsive UI and eliminating the flicker of the page refresh. Currently, since the entire page is refreshed, a lot of data needs to be transmitted because the entire page must be resent. If you used Ajax, the server could have sent back a 500-byte message containing the thank you message instead of sending 26,813 bytes to refresh the entire page. Even when using high-speed Internet, the difference between transmitting 26K and 1/2 K is
Advanced Java Programming Unit 9
Sikkim Manipal University Page No. 244
significant! Of equal importance, instead of redrawing the entire screen, only the small section regarding votes would need to be redrawn.
Let's implement our own rudimentary voting system that leverages Ajax.
Raw Ajax: Using the XmlHttpRequest Directly.
As alluded to above, the heart of Ajax is the XmlHttpRequest JavaScript object. The following sample article ranking system was built to walk you though the low-level basics of Ajax: http://tearesolutions.com/ajax-demo/raw-ajax.html. Note: If you've already installed the ajax-demo.war in your local WebLogic container, you can navigate to http://localhost:7001/ajax-demo/raw-ajax.html.
Browse the application, cast some votes, and witness firsthand how it behaves. Once you're familiar with the application, continue reading to dig into the details of how it works.
First, you have some simple anchor tags that link to a JavaScript castVote(rank) function.
function castVote(rank) {
var url = "/ajax-demo/static-article-ranking.html";
var callback = processAjaxResponse;
executeXhr(callback, url);
}
This function creates a URL for the server resource you want to communicate with, and calls your internal executeXhr function, providing a callback JavaScript function to be executed once the server response is available. Since I need this to run on a simple Apache setup, the "cast vote URL" is just a simple HTML page. In real life, the URL called would tally the votes and dynamically render a response with the vote totals.
Advanced Java Programming Unit 9
Sikkim Manipal University Page No. 245
The next step is the spawning of an XmlHttpRequest request:
function executeXhr(callback, url) {
// branch for native XMLHttpRequest object
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = callback;
req.open("GET", url, true);
req.send(null);
} // branch for IE/Windows ActiveX version
else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = callback;
req.open("GET", url, true);
req.send();
}
}
}
As you can see, executing a XmlHttpRequest is not trivial, but it is straightforward. As always in JavaScript land, the majority of the effort is spent ensuring browser compatibility. In this case, you first determine if the XmlHttpRequest object is available. If it is not, you are likely dealing with Internet Explorer, in which case you use the ActiveX implementation provided.
The most relevant part of the executeXhr() method is these two lines:
req.onreadystatechange = callback;
req.open("GET", url, true);
Advanced Java Programming Unit 9
Sikkim Manipal University Page No. 246
The first line defines the JavaScript callback function you want to be automatically executed once the response is ready, and the "true" flag specified in the req.open() method means you want to execute this request asynchronously.
Once the XmlHttpRequest is processed by the server and returned to the browser, the callback method that you set using the req.onreadystatechange assignment will be automatically invoked:
function processAjaxResponse() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
$('votes').innerHTML = req.responseText;
} else {
alert("There was a problem retrieving the XML data:\n" +
req.statusText);
}
}
}
This code is quite terse and uses a few magic numbers, which makes it hard at first to understand what is happening. To clarify this, the following table (borrowed from http://developer.apple.com/internet/webcontent/ xmlhttpreq.html) details the common XmlHttpRequest object properties.
Property
Description
Onreadystatechange
Event handler for an event that fires at every state change
ReadyState
Object status integer:
0 = uninitialized
1 = loading
2 = loaded
Advanced Java Programming Unit 9
Sikkim Manipal University Page No. 247
3 = interactive
4 = complete
ResponseText
String version of data returned from server process
ResponseXML
DOM-compatible document object of data returned from server process
Status
Numeric code returned by server, such as 404 for "Not Found" or 200 for "OK"
StatusText
String message accompanying the status code
Now the processVoteResponse() function makes a bit more sense. You first check the overall status of the XmlHttpRequest to ensure it is complete (readyStatus == 4), and then you interrogate the request status as set by the server. If everything is OK (status == 200), you proceed to rewrite the contents of the "votes" node of your DOM by using the innerHTML attribute.
Now that you see firsthand how the XmlHttpRequest object works, let's abstract away the gory details by leveraging a framework built to simplify asynchronous JavaScript communication with Java applications.
9.4 Summary
The term Ajax is used to describe a set of technologies that allow browsers to provide users with a more natural browsing experience.
It's really several technologies, each flourishing in its own right, coming together in powerful new ways. Ajax incorporates:
 Standards-based presentation using XHTML and CSS
 Dynamic display and interaction using the Document Object Model
 Asynchronous server communication using XMLHttpRequest JavaScript binding everything together.
9.5 Terminal Questions
1. What do you mean by AJAX?
2. How does AJAX works? Explain with an example?

No comments:

Post a Comment