Thursday, June 25, 2009

Java Ajax

Ajax - stands for Asynchronous Javascript and XML. With Ajax web pages interact with Server asynchronously in the background without affecting the display/behaviour of the page. It provides rich user experince comapred to old page refresh model. I uses javascript to connect server using XML Http Request.

"Ajax isn't a technology. It's really several technologies, each
flourishing in its own right, coming together in powerful new ways. Ajax
incorporates:

Ajax is also a key component of Web 2.0







XML Http Request(XHR)


To show how Ajax works Here is the simple code that parses an .xml file located in server and display it is web page


states.xml

<?xml version="1.0" encoding="UTF-8"?>

<Items>

<Option value="CA">California</Option>

<Option value="IL">Illinois</Option>

</Items>


Server side code say AjaxTestServlet


try{

javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

dbf.setValidating(false);

javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder();

String file = request.getParameter("file");

org.w3c.dom.Document doc = parser.parse("http://localhost/<appcontext>/"+file);

org.w3c.dom.NodeList nList = doc.getElementsByTagName("Option");

int len = doc.getElementsByTagName("Option").getLength();

StringBuffer buff = new StringBuffer();

buff.append("<?xml version='1.0' encoding='UTF-8' ?><items>");

String attrib = "";

String val = "";

for(int i=0;i<len;i++){

attrib = nList.item(i).getAttributes().getNamedItem("value").getNodeValue();

val = nList.item(i).getChildNodes().item(0).getNodeValue();

buff.append("<option value='"+attrib+"'>"+val+"</option>");

}



buff.append("</items>");



response.setContentType("text/xml");

response.setHeader("Cache-Control","no-cache");

response.getWriter().write(buff.toString());

}catch(Exception e){

e.printStackTrace();

}

Client Side say test.html

create xhr object
var xmlHttp;

function createXMLHttpRequest() {

if(window.ActiveXObject) {

xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

} else if(window.XMLHttpRequest) {

// Firefox, Opera 8.0+, Safari

xmlHttp = new XMLHttpRequest();

}

}

response handler


function handleServerResponse() {

var elements ;

var elemSize ;

var server_response = "";

if(xmlHttp.readyState == 4) { // the state when the request has completed

if (xmlHttp.status == 200) { // the status code returned from the server

elements = xmlHttp.responseXML.getElementsByTagName("option");

elemSize = elements.length;

for(var i=0;i<elemSize;i++) {

server_response = server_response+elements[i].getAttribute("value")+" : "+elements[i].firstChild.data+"<br>";

}

}else{

server_response='No Data';

}



}



document.getElementById("mydiv").innerHTML = "<table><tr><td>"+server_response+"</td></tr></table>";



}

request handler


function doProcess(fileName){

createXMLHttpRequest();

xmlHttp.open("GET", "testAjaxProcess.jsp");

xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

xmlHttp.send("file="+fileName);

xmlHttp.onreadystatechange = handleServerResponse;

return false;

}

html code


<a href="#" onclick="javascript:doProcess('states.xml')">STATES</a>
<div id="mydiv">&nbsp;</div>

Output :

CA : California
IL : Illinois

There are many open source frameworks availabe to implement Ajax. But I would suggest to start with raw code to know working of actual objects


No comments:

Post a Comment