AJAX - The Complete Reference

(avery) #1

Chapter 2: Pre-Ajax JavaScript Communications Techniques 37


PART I


if (responseImage.height == "2")
target.innerHTML = "Server available. Connection time approximately "
+ responseImage.width + "ms.";
else
target.innerHTML = "Server unavailable.";

You can see the communication trace here, which illustrates this process.

This approach is very limited as there are only two dimensional values that have to be
encoded as simple integers that can be passed back. Fortunately, it turns out that if this
method is used in conjunction with a cookie, all sorts of data can be passed back to the
browser in response to an image request.

Images and Cookies Technique
To expand the image communication pattern to a truly valuable two-way method, we add
in a batch of cookie power. The ever-present rating example can be extended to respond
with the user’s rating, the current average rating, and the total number of votes. On the
server side, the user’s vote is received via the query string and the results are sent back via
a cookie that is associated with a blank pixel.gif response.

if ($response == "cookie")
{
$results = $rating. "a". $average. "a". $votes;

//send an image back
$filename = 'pixel.gif';
$fp = fopen($filename, 'rb');

header("Content-Type: image/gif");
header("Content-Length: ". filesize($filename));

//set the cookie
setcookie("PollResults", $results, time()+3600, "/", "ajaxref.com");
Free download pdf