AJAX - The Complete Reference

(avery) #1

32 Part I: Core Ideas


chapter, some examples will be shown that illustrate that even in the modern Ajax world,
there are plenty of useful applications for the one-way communication pattern using
traditional JavaScript communication mechanisms.

Two-way Communications


Traditional JavaScript supported numerous ways to accomplish two-way communication;
in fact, the same set of approaches from the previous sections can be extended to perform
this. Of course, some of these techniques are better than others, particularly the iframes and
script approaches, which have a bit more flexibility than others.

Images for Two-way Communications

It would seem that using an image is likely not the best way to transmit two-way information.
Consider that if you ask for an image you are going to be receiving an image, likely in GIF,
JPEG, or PNG format for display. As an example, you can ask the user for some data and then
generate a custom image for them. The transmission of the user-supplied data is via the query
string as before, but this time the server will respond not with a 204 code but an actual image
to use. You can then use the DOM and insert it into the page.
Yet there are changes to consider now that this is a two-way communication. The browser
normally provides a number of clues such as a pulsating logo, an hour glass icon, and status
bar changes to inform the user that communication is taking place, but when this is performed
via JavaScript many of these feedback mechanisms will be silent. It is important to show the
user some form of request status, usually with a message or animated GIF that spins,
bounces, or whatever else you can think of to mesmerize the user long enough to prevent
them from getting annoyed and leaving.

Putting a status indicator in the page is a matter of finding the appropriate spot—likely
near the user’s last point of focus—and then using the DOM to insert it.

/* set up status image */
var statusImg = document.createElement("img");
statusImg.id = "progressBar";
statusImg.border=1;
statusImg.src = "progressbar.gif";
target.appendChild(statusImg);

You’ll see in later chapters, particularly Chapter 8, that such status systems, while
somewhat helpful, really could be much more informative, especially in the case of long
running processes such as file uploads. However, this adds a bit too much complexity at this
point so let’s stick with the simple activity animation.
Now that the client is waiting for a response from the server, the script needs to “wake
up” when data is available. This idea is called a callback and it is used in most forms of
JavaScript communications. In the case of using an Image object to communicate, a function
can be associated with the object’s onload event.

var currentRequest = new Image();
currentRequest.onload = handleResponse;
Free download pdf