Lucky Dip Logo
Powered by PlusNet. PlusNet broadband.
Patrick's Lucky Dip
Home > Java > JSP Tutorial > Simple AJAX

Patrick Haston
18 February 2009

JSP Tutorial - Simple AJAX

AJAX stands for Asynchronous JavaScript and XML and can seem difficult to learn. Even the full name sounds complicated. Luckily for us it can be made quite simple.

With AJAX, you will need two pages. One is the page that your customer uses, the other is called behind the scenes. In our little example we're going to have a drop down list of passtimes. When a selection is made, we're going to show a little message. I've kept it simple so the AJAX code is lost in the clutter.

Here's the page which returns a message. I've called it lookup.jsp and it takes a parameter called parameter. Not very imaginative I know, but easy to remember. Here's the code:

<%@ page contentType="text/html;charset=windows-1252"%>

<%

String parameter = "";
String html = "I wouldn't do that if I were you.";

try
{
  parameter = request.getParameter("parameter");
  
  if( parameter == null || parameter.length() == 0 ) html = "";
  else
  {
    if( parameter.equalsIgnoreCase("TV") ) 
      html = "Watching too much television is bad for your eyes.";
    if( parameter.equalsIgnoreCase("music") ) 
      html = "Listening to loud music can damage your ears.";
    if( parameter.equalsIgnoreCase("games") ) 
      html = "Playing computer games can give you RSI.";
  }
}
catch( Exception e )
{
  html = "Error: " + e.getMessage();
}

%>

<%=html%>

You'll see that there are two String variables: one called parameter which is set to whatever the parameter on the url is. The html parameter is set depending on the value of parameter. You may notice that there's none of the usual html tags that you normally see: that's deliberate. You can run this directly and test it works by using the url lookup.jsp?parameter=music.

Now that's working, let's look at the main page. This looks a bit daunting at first as it's got a chunk of JavaScript in it, but I'll break it into small bite-sized bits for you.

Here's the code for your main jsp page:

<%@ page contentType="text/html;charset=windows-1252"%>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>AJAX Example 1</title>
    <script language="JavaScript">
var xmlHttp;

function show_lookup(value)
{ 
xmlHttp=GetXmlHttpObject();

if (xmlHttp==null)
 {
 alert ("Browser does not support HTTP Request");
 return;
 }
var url = "lookup.jsp?parameter=" + value + "&random=" + Math.random();
xmlHttp.onreadystatechange = stateChanged;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}

function stateChanged() 
{ 
if ( xmlHttp.readyState == 4 || xmlHttp.readyState == "complete")
 { 
  document.getElementById("lookup_result").innerHTML = xmlHttp.responseText;
 } 
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 //Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}    
    </script>
  </head>
  <body>
  
    Select your favourite passtime from the list:
    <select onchange="show_lookup(this.value);">
      <option value="">Select one...</option>
      <option value="TV">Watching television</option>
      <option value="music">Listening to music</option>
      <option value="games">Playing computer games</option>
      <option value="other">Something else</option>
    </select>
    
    <div id="lookup_result">
    </div>
  
  </body>
</html>
  

Ok, lets start by looking at the JavaScript. The first line sets a global variable called xmlHttp. This is used by all of the three functions which is why it is declared outside of them. The function that is called first is show_lookup(value). The parameter value will be set to the code we want to pass to the lookup.jsp page.

The first thing we do is call the GetXmlHttpObject() function to set the xmlHttp variable. This function tries several different ways of doing this depending on the type of brower. Don't worry about trying to understand it - it works.

The next thing we do (assuming that xmlHttp got set properly) is to define the page that we want to call. We can declare a variable called URL and set it to the page we want to call. We can add on to this any parameter value pairs that we need, and it's a good idea to add on a random number to prevent a previously cached page from being returned. This wouldn't be a problem in our example, but it's good practice to include it, especially if me you tend to cut and paste chunks of code between projects.

The next three lines set properties and call functions of the xmlHttp object. The first is to tell it what function to call every time the status of the object changes. Then we tell it to what command we want, in our case to open a web page using the standard GET method, the url of the page. I don't know that the third parameter does, but setting it to true works for me.

Our stageChanged() function only checks for the status changing to complete, but you could also check for other states if you wished. When the stageChanged() function is finally called with a status of complete, we use document.getElementById("lookup_result").innerHTML = xmlHttp.responseText to set the appropriate part of our page with the entire text of the called page.

Now you'll understand why our lookup.jsp page didn't have any extra html tags: we would just have had to strip them out again. What I often do is get the lookup.jsp page to return the html for a second select combo box where the elements are dependant on the value of the first select box, say a list of employees in the selected department.

The body of the page contains a simple little select combo box. It's nothing special, but the key thing to notice is the onchange="show_lookup(this.value);" attribute of the select box. This is what calls the JavaSript function to go off and do something. The div below is where the results will appear.

Strictly speaking, this isn't true AJAX as we don't bother with XML, we're just going straight for html. This keeps things simple and is probably fine for most of your applications.