Sunday 20th of May 2012 04:29:47 PM

AJAX in Action

Ajax Tutorial - This is how Ajax works

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. After spending some time learning what AJAX is all about. Here is real working example of AJAX for a perfect scenario and how we are using it in JavaRSS.com.

What is AJAX: AJAX is an architecture and not a technology. AJAX stands for Asynchronous JavaScript And XML.

Punch Line: Lazy loading.

Problem: When JavaRSS.com homepage loads, it loads the description of all the items (if you have it enabled in settings). The description is not visible until you hover the mouse over the item.

The problem is that the user may not hover the mouseover every item on every channel. So pre loading all description is not good.

Solution: Using AJAX, the item description is loaded dynamically from the server only on mouseover.

This will reduce the initial page load size by more than half, there by loading the page faster for a better user experience.

Sequence Diagram:

AJAX Sequence Diagram

We will first call the JavaScript function getDescription on onmouseover event. Here is the html code:

<a href="/" onmouseover="getDescription(3,1)">Java & J2EE News<a>
Here is the code for Javascript getDescription function:
var url = 'http://localhost:8080/getDescription.jsp?channelId=' + channelId + '&itemId=' + itemId;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.onreadystatechange = processRequest;
req.open("GET", url, true);
req.send(null);

The XMLHttpRequest object will be doing the http connection to retrive the xml document. We will check to see if it is IE or not and create the XMLHttpRequest object.

if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}

Set the callback function, and send the HTTP "GET" request to the server for the xml document:

req.onreadystatechange = processRequest;
req.open("GET", url, true);
req.send(null);

The JSP will create the xml document with the approriate description for the channel and item numbers.

<%
While some other pseudo-classes, like :link and:visited , are constrained to theA element in HTML, the same is not true of:hover. User agents could, in theory, allow theassignment of hover styles to any element, like this:

P:hover {font-weight: bold;}

Therefore, if you want to make sure your hover styles are appliedonly to your hyperlinks, you would need to use this rule:

String channelId = request.getParameter("channelId"); String itemId = request.getParameter("itemId"); String description = "This is the description for the channelId: " + channelId + "and itemId: " + itemId; if (description != null) { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); } else { response.setStatus(HttpServletResponse.SC_NO_CONTENT); } %>

Check for the response code for the HTTP request. Status is 200 for "OK".

function processRequest() {
if (req.readyState == 4) {
if (req.status == 200) {
parseMessages();
} else {
alert ( "Not able to retrieve description" );
}
}
}

The readyState is 4 if the document is loaded.

readyState Status Codes:
0 = uninitialized
1 = loading
2 = loaded
3 = interactive
4 = complete

Finally, we now parse the XML document to retrive and show the description.

Problems: The only problem, I encountered is the "&" character. The "&" is not a valid character in XML document. So I had to convert it to "&amp;".

function parseMessages() {
response  = req.responseXML.documentElement;
itemDescription = response.getElementsByTagName('description')[0].firstChild.data;
alert(itemDescription);
}

Here is the code all together:

HTML Code:
<a href="/" onmouseover="getDescription(3,1)">Java & J2EE News<a>
JavaScript Code:
function getDescription(channelId,itemId) {
var url = 'http://localhost:8080/getDescription.jsp?channelId=' + channelId + '&itemId=' + itemId;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.onreadystatechange = processRequest;
req.open("GET", url, true);
req.send(null);
}
function processRequest() {
if (req.readyState == 4) {
if (req.status == 200) {
parseMessages();
} else {
alert ( "Not able to retrieve description" );
}
}
}
function parseMessages() {
response  = req.responseXML.documentElement;
itemDescription = response.getElementsByTagName('description')[0].firstChild.data;
alert ( itemDescription );
}
JSP Code:
<%
String channelId = request.getParameter("channelId");
String itemId = request.getParameter("itemId");
description = "This is the description for the channelId: " + channelId + "and itemId: " + itemId;
if (description != null) {
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");


} else {
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
%>

About the author: Jay has more than 10 years of experience in IT industry and have been working with Java & J2EE ever since they were born.

standard color values for these names. Declaring that an elementshould be colored orange doesn't mean thatdifferent browsers, or even the same browser running on differentplatforms, will produce exactly the same shade of orange. With thesixteen standard colors, there is at least some hope that they willappear as similar as possible, because the color values for thesesixteen are defined. Beyond those, all bets are off. Browsers mayimplement similar shades for the same color name, or they may not;the differences may be imperceptible to the eye, or so obvious thatthey're almost jarring. Web servers typically have 3- or 4-part names; the last two parts comprise the registered domain name, e.g., udel.edu.  Some web servers are configured as virtual hosts serving files under multiple server names and domains.

The path and filename in a URL are typically specified from the root of the web-server directory, which is some subdirectory of the server's local file system.  For security reasons, browsers can't access stuff outside the web-server directory. 

URLs can specify files by  relative or absolute path. 

Then you decide that you want all table cells with a class of highlight to contain yellow text:

TD.highlight {color: yellow;}

This sets the foreground color of all elements within any table cell with a class of highlight to be yellow, as shown in Figure 6-2:

Figure 6-2

Figure 6-2. Highlighting a table cell contents