Magazine
 
Quick Review:Ajax
 
Ajax Examples
 

xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
var name = document.getElementById(‘name’).value;
document.getElementById(‘time’).innerHTML = “<br/>Welcome <b> “+name+”<hr/
>Current Server Time is:</b> <font color=’red’ size=’5'>” + xmlHttp.responseText + “</
font>”;;
}
}
var url = “time.jsp”;
xmlHttp.open(“GET”,url,true);
xmlHttp.send(null);
}
</script>
<form>
Enter Your Name: <input type=”text” onkeyup=”ajaxFunction();” name=”name” id=”name”/>
<div id=”time” ></div>
</form>
</body>
</html>

The input text field for user name has “onkeyup” attribute, which is set to the JavaScript function “ajaxFunction()”. This method is called every time user leaves the key to move up after pressing the key down. The “div” tag having “id” attribute as “time” is the area where the time is to be displayed.

Ajax code starts from here. “ajaxFunction()” first tries to get HTTP request object maintaining the browser compatibility. In this example, this object is stored in the variable named “xmlHttp”. Read how to get HTTP request object on page 12

Next step is to determine which method should be invoked after getting the response from the server. In this example method is defined anonymously at the right place. Now the request for the JSP page “time.jsp” is forwarded to the server.

time.jsp:

<%@page contentType=”text/html” import=”java.util.*” %>
<%
response.getWriter().write((new Date()).toString());
%>

The server executes the JSP code, which sends current date as a response. After getting the response from the server the anonymous function is executed.

if(xmlHttp.readyState==4){
var name = document.getElementById(‘name’).value;
document.getElementById(‘time’).innerHTML = “<br/>Welcome <b>
“+name+”<hr/>Current Server Time is:</b> <font color=’red’ size=’5'>” +
xmlHttp.responseText + “</font>”;
}

Apr 2008 | Java Jazz Up | 17
 
previous
index
next
 
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

30
, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

58
, 59, 60, 61, 62, 63 , 64, 65 , 66 , 67 , 68 , 69 , 70, 71, 72, 73, 74, 75, 76, 77, 78,   Download PDF