AJAX - The Complete Reference

(avery) #1

Chapter 2: Pre-Ajax JavaScript Communications Techniques 33


PART I


Of course, more likely a closure will be used to wrap the function so that variables can
be preserved and passed rather than rely on global variables.

currentRequest.onload = function(){handleResponse(target,currentRequest,timer);};

This style of JavaScript will be seen frequently in Ajax applications.
Given that it is possible that the image may not come back properly, it is also important
to address error conditions. A simple approach using the image communication technique is
to set up a callback in the case of the Image object firing its onerror event.

currentRequest.onerror = function(){cancelRequest(target, "Server error",current
Request,timer);};

It is also important to address the possibility that the response image is not generated in a
timely manner. To mitigate such a problem we can set a timeout value, and if the timer fires
before receiving the image, alert the user.

/* function to cancel request if network timeout occurs */
networkTimeout = function(){cancelRequest(target, "Network timeout",currentRequest);};
/* define network timeout in milliseconds and bind to timeout function */
var timer = setTimeout("networkTimeout()",timeout*1000);

When employing this technique, it is important to clear any timeouts that may be running if
data is received successfully.
One final change to note is the need to be very aware of the browser’s cache now that
content is being returned. Given that a cacheable GET request is sent, either appropriate
headers must be set by the server or some value must be added to the URL to make it
unique so that the browser returns new images rather than cached ones. To do this simply,
a timestamp is added to the payload.

/* Make timestamp to prevent caching */
var timeStamp = (new Date()).getTime();
/* Form payload with escaped values */
var payload = "username=" + encodeValue(userName);
payload += "×tamp=" + encodeValue(timeStamp);

The full example is shown here and demonstrated in Figure 2-5. It can also be run online
at http://ajaxref.com/ch2/imagegenerator.html.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/
xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Chapter 2 : Image Generation</title>
<script type="text/javascript">
function encodeValue(val)
{
var encodedVal;
if (!encodeURIComponent)
{
encodedVal = escape(val);
/* fix the omissions */
Free download pdf