AJAX became popular with the launch of Google Suggest, which uses XMLHttpRequest dynamically suggest the user with search keywords.
Using XMLHttpRequest
IE uses an Activex component called Msxml2.XMLHTTP to generate XMLHttpRequest objects, while browsers like Mozilla, Opera and Netscape uses the JavaScript XMLHttpRequest object.
We need to create an XMLHttpRequest object to hold the request and despatch it to the server.
We also need to define a method, that receivess the response from the server. This is done by assigning the onreadystatechange property with the javascript function that will receive the response.
There is a readyState property, which represents the status of the server response. Each time the state is changes, the function defined in onreadystatechange will be invoked.
Here are the different ready states
0 - Request Uninitialized
1 - Request Initialized
2 - Request Sent
3 - Request Delivered
4 - Response Received
The responseText property is used to retrieve the response sent back from the server.
Here is a small AJAX based JSP Shopping Cart Application. The user is permitted to add and remove items to the shopping cart, from the list of available items.
Each request to add or remove an item creates a new XMLHttpRequest object having the onreadystatechange property set to getReadyStateHandler function, and then posted to the web server.
function addToCart(itemCode) {
var req = newXMLHttpRequest();
req.onreadystatechange = getReadyStateHandler(req, updateCart);
req.open("POST", "cart.do", true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send("action=add&item="+itemCode);
}
function removeFromCart(itemCode) {
var req = newXMLHttpRequest();
req.onreadystatechange = getReadyStateHandler(req, updateCart);
req.open("POST", "cart.do", true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send("action=remove&item="+itemCode);
}
The getReadyStateHandler function checks the ready states, and if a response is received, checks the response code, and if it is an HTML status code 200, extracts the response from XMLHttpRequest and designates the javascript updateCart function to handle the response.
function getReadyStateHandler(req, responseXmlHandler) {
// Return an anonymous function that listens to the XMLHttpRequest instance
return function () {
// If the request's status is "complete"
if (req.readyState == 4) {
// Check that we received a successful response from the server
if (req.status == 200) {
// Pass the XML payload of the response to the handler function.
responseXmlHandler(req.responseXML);
} else {
// An Error occurred
alert("HTTP error "+req.status+": "+req.statusText);
}
}
}
}
The updateCart function takes in the response as the input parametar and updates - adds or removes items - in an unordered list - <ul> identified by the name "contents"
function updateCart(cartXML) {
var cart = cartXML.getElementsByTagName("cart")[0];
var generated = cart.getAttribute("generated");
if (generated > lastCartUpdate) {
lastCartUpdate = generated;
var contents = document.getElementById("contents");
contents.innerHTML = "";
var items = cart.getElementsByTagName("item");
for (var I = 0 ; I < items.length ; I++) {
var item = items[I];
var name = item.getElementsByTagName("name")[0].firstChild.nodeValue;
var quantity = item.getElementsByTagName("quantity")[0].firstChild.nodeValue;
var listItem = document.createElement("li");
listItem.appendChild(document.createTextNode(name+" x "+quantity));
contents.appendChild(listItem);
}
}
document.getElementById("total").innerHTML = cart.getAttribute("total");
}
The complete example package can be downloaded from here. Copy the war file to the webapps directory of your Apache Tomcat installation. This will be unpacked automatically in Tomcat.(You may use any other web server as the case may be). In your browser, type in the url: http://localhost:8080/AjaxTest to see AJAX in Action.
No comments:
Post a Comment