AJAX

AJAX is a collection of related web technologies that help to make interactive web applications. The term actually stands for Asynchronous JavaScript and XML and is aimed at increasing responsiveness and interactivity of web material.

Using AJAX requires that you work with JavaScript and have some experience with the structure of an HTML document. However, it is quite straightforward to work with AJAX in webMathematica.

Time Example

webMathematica contains a simple example of working with AJAX. The source for this can be found in the webMathematica web application in the directory Examples/AJAX (the full path in Tomcat would be webapps/webMathematica/Examples/AJAX). The two files are LoadDate.jsp, which contains the AJAX code to call to the server, and ReturnDate.jsp, which returns the result from the server. If your server is configured and running, you can test this example with the URL http://localhost:8080/webMathematica/Examples/AJAX/LoadDate.jsp. (You may have some other URL for accessing your server.)

LoadDate.jsp contains two sections, a JavaScript section and an HTML section. The JavaScript is as follows (in a real usage, this would be better put into a js library file rather than directly into the web page).

<script>
function loadDate( ) {
var xmlHttp;
try { // Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
if (xmlHttp.overrideMimeType) {
xmlHttp.overrideMimeType('text/plain');
}
}
catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
var elem = document.getElementById("time");
elem.value = xmlHttp.responseText;
}
}
var fullDate = document.getElementById("fullDate").checked;
var url = "ReturnDate.jsp";
url=url+"?fullDate="+fullDate;
xmlHttp.open("POST", url, true);
xmlHttp.send(null);
}
</script>

The first part of this example involves obtaining an instance of an XMLHttpRequest object. In this example, the instance is called xmlHttp. Note how different techniques are used for different browsers.

The XMLHttpRequest object is a major part of AJAX; this allows the asynchronous interaction, set up by the onreadystatechange function. This is called when there is a change in the state of the HTTP request. The change that this example tracks is when the readyState goes to 4, which means that the request is complete. When this happens the function takes the text in the response and inserts it into the time element of the web page. The onreadystatechange function is called asynchronously at some time in the future when the HTTP request is complete. The details of how this is done is completely left up to the XMLHttpRequest object, which leads to a tremendous simplification for the AJAX programmer.

After the result handler is set up, the actual request is made. This is done by setting up the URL to call, which includes an input parameter taken from the value of the checkbox in the HTML. After the send call, the request is triggered.

The HTML part of the page is as follows.

<h1>
AJAXDemo
</h1>
<p>
A basic AJAX example.
</p>

Result: <input type="text" id="time" />
<br/>
<br/>
<p> Full Date: <input type="checkbox" id="fullDate" /></p>

<button onclick="loadDate()">Update</button>

Some of this is concerned with the content of the page, such as the title, while other parts work with the interactive content. Note the button element. When this is clicked the loadDate() JavaScript function, which you saw above, is called. This means that when you click the button, the time input field is updated with the result of the web request.

On the server there is a different page, ReturnDate.jsp, which actually does the server work. It is quite simple and is shown below.

<%@ taglib uri="http://www.wolfram.com/msp" prefix="msp" %>

<msp:evaluate>
If[ $$fullDate === "true",
DateString[],
DateString[{"Hour", ":","Minute",":","Second"}]]
</msp:evaluate>

There is one evaluation carried out by Mathematica; this checks the setting of the fullDate input parameter (which came from the checkbox in the original web page). It returns a string of the date.

Note how the page does not need any HTML formatting because the result is just a string that is used by the loadDate() JavaScript function. Also, note how the page displayed in the browser does not change; only part of the page changes. This can help to improve performance, since less is transmitted. Also, it can improve appearance since the whole page does not flicker. Another benefit is that other effects can be added, for example, while the browser is waiting for the result to come back it could do something to indicate that the page is waiting for something.

HTML Example

AJAX techniques are not limited to string results from the server. In fact, the server can return with many differrent types of format, and these can be used to change the contents of the document in the browser. This example shows how the src attribute of an img tag can be changed.

The source for this example can be found in the webMathematica web application in the directory Examples/AJAX (the full path in Tomcat would be webapps/webMathematica/Examples/AJAX). The two files are LoadImage.jsp, which contains the AJAX code to call to the server, and ReturnImage.jsp, which returns the result from the server. If your server is configured and running you can test this example with the URL http://localhost:8080/webMathematica/Examples/AJAX/LoadImage.jsp. (You may have some other URL for accessing your server.)

First, this is the source of ReturnImage.jsp, which is similar to ReturnDate.jsp except that it returns an HTML fragment (this is done with MSPShow); it also sets the content type to be text/xml.

<%@ page contentType="text/xml"%> 
<%@ taglib uri="http://www.wolfram.com/msp" prefix="msp" %>

<msp:evaluate>
fun = If[ MSPValueQ[ $$fun] && $$fun =!= "",
MSPToExpression[ $$fun],
Sin[x]];
p = Plot[ fun, {x,0,10}];
MSPShow[p]
</msp:evaluate>

You can test this with the URL http://localhost:8080/webMathematica/Examples/AJAX/ReturnImage.jsp. You should see something like the following.

<img src="/webMathematica/MSP/MSP22363103587829853091_81?MSPStoreType=image/gif" /> 

Thus the page returns a fragment of HTML, not a complete document. The JavaScript function takes this fragment and inserts it into the document.

Here is the JavaScript function in LoadImage.jsp. It is quite similar to LoadDate.jsp.

<script>
function loadImage( ) {
var xmlHttp;
try { // Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
if (xmlHttp.overrideMimeType) {
xmlHttp.overrideMimeType('text/xml');
}
}
catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
var xmlData = xmlHttp.responseXML;
var imgNode = xmlData.getElementsByTagName('img')[0];
var srcAttr = imgNode.attributes.getNamedItem("src");
var srcTxt = srcAttr.nodeValue;
var elem = document.getElementById("image");
elem.src = srcTxt;
}
}
var fun = document.getElementById("fun").value;
var url = "ReturnImage.jsp";
url=url+"?fun="+fun;
xmlHttp.open("POST", url, true);
xmlHttp.send(null);
}
</script>

The main difference here is the function that takes the result. It takes this as XML and does some processing on the result to find the value of the src attribute, which it sets into an img tag present in the page.

The HTML part of the page is as follows.

<h1>
AJAX Image Demo
</h1>
<p>
A basic AJAX example that loads an image.
</p>

Function: <input type="text" id="fun" />
<br/>
<br/>
<img id="image" />
<br/>
<br/>
<button onclick="loadImage()">Update</button>

Some of this is concerned with the content of the page, such as the title, while other parts work with the interactive content. Note the img tag labeled image, which has its src attribute filled out by the JavaScript function when the HTTP call is finished.

One important point about this example is how the client side JavaScript function can work with the XML. In this case the XML is XHTML, but in general it might be any form of XML.

Web Services and XML Exchange

The AJAX model is quite close to a web service. In fact, the techniques for setting up an AJAX interaction, particularly on the server, are closely related to informal web services, which are discussed in a later section. There is also an example of an informal web service that uses AJAX.