There are several third party libraries that simplify the programming that is needed to make your web pages communicate with the server more dynamically, and without doing complete page reloads. However, some of you may be interested in knowing how exactly AJAX functionality can be added to your web sites and without involving any 3rd party software. Below is a complete example. There are 2 source files. The first one is the HTML code. The second one is a JSP file, which handles the AJAX request on the server.

The HTML file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="" xml:lang="en">
    <title>My Web Site</title>
    <meta http-equiv="Content-Script-Type" content="text/javascript" />
    <meta http-equiv="Content-Style-Type" content="text/css" />
    <script type="text/javascript">
      // <![CDATA[
      function getXMLHttpRequest(){
            var a=['Microsoft.XMLHTTP','Msxml2.XMLHTTP','Msxml2.XMLHTTP.3.0',
            var i=a.length;
            while(i--){try{return new ActiveXObject(a[i]);}catch(e){}}
        if(window.XMLHttpRequest){try{return new XMLHttpRequest();}catch(e){}}
        return null;
      function getTime() {
        var r=getXMLHttpRequest();
          var tb=(new Date()).getTime(); // Random value to prevent caching.
          var pl="task=getTime&rid="+tb;
            "Content-Type", "application/x-www-form-urlencoded");
            alert("Could not send the request: " + e);
      function getResult(r) {
            alert("Server responded with code " + r.status);
      // ]]>
    <form action="">
        <input type="button" value="Get server time" onclick="getTime()"/>
        <div id="serverTime"></div>

The JSP file:

<%@ page import="java.util.Date"
%><%@ page contentType="text/xml"
    String task = request.getParameter("task");
    if ("getTime".equals(task)) {
        String serverDate = (new Date()).toString();
        %><?xml version="1.0"?><response><%=serverDate%></response><%
    } else {
        %><?xml version="1.0"?><response>Invalid server request</response><%

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.