Wednesday, January 25, 2012


Simple AJAX Program

Simple AJAX application using java script and JSP.


Files required.

1. ajax.js
2. mainpage.jsp
3. process.jsp
4. web.xml

Code :


1. ajax.js



var xmlHttp;
function postRequest(url) {


if (window.XMLHttpRequest) { // Mozilla, Safari, ...
//alert("other than IE");
 xmlHttp = new XMLHttpRequest();


} else if (window.ActiveXObject) { // IE
//alert("IE only");
 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");


}


xmlHttp.open('POST', url, true);
xmlHttp.onreadystatechange = function() {

if (xmlHttp.readyState == 4) {
updatepage(xmlHttp.responseText);


}


}


xmlHttp.send(url);


}




function updatepage(str){


document.getElementById("result").innerHTML = "<font color='green' size='15'>" + str + "</font>";


}


function showCurrentTime(){


var url="process.jsp";
postRequest(url);


}


2. mainpage.jsp



<%@ page import="java.util.*" %>
<html>
<head>


<title>Ajax Example</title>
<script type="text/javascript" src="ajax.js"> </script>
</head>


<body>


<h1 align="center"><font color="#000080">Ajax Example</font></h1>
<%
out.println(new Date());
%>
<p><font color="#000080">&nbsp;This very simple Ajax Example retrieves the
current date and time from server and shows on the form. To view the current
date and time click on the following button.</font></p>


<form name="f1">


<p align="center"><font color="#000080">&nbsp;<input value=" Show Time " 
type="button" onclick='JavaScript:showCurrentTime()' name="showdate"></font></p>
<div id="result" align="center"></div>


</form>
<div id=result></div>
</body>


</html>




3. process.jsp



<%@ page import="java.util.*" %>
<%
out.println(new Date());
%>


4. web.xml



<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>AjaxApp1</display-name>
  
  <welcome-file-list>
      <welcome-file>mainpage.jsp</welcome-file>
    
  </welcome-file-list>
</web-app>