AJAX - The Complete Reference

(avery) #1

38 Part I: Core Ideas


// dump the response image and end the script
fpassthru($fp);
exit;
}

When the image arrives, the result is read from the cookie in the script’s response callback
function. While this sounds easy enough, reading the cookie properly does require a bit of
string manipulation as shown in the next code fragment.

function readCookie(name)
{
var nameEQ = name + "=";
var ca = document.cookie.split(";");
for (var i=0;i < ca.length;i++)
{
var c = ca[i];
while (c.charAt(0)== " ")
c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length,c.length);
}
return null;
}

var results = readCookie("PollResults");

With the response in hand and unpacked from the cookie, it is put in the page using
basic DOM methods.

/* Analyze the results */
var rating, average, total;
rating = average = total = 0;
var resarray = results.split("a");
if (resarray.length == 3)
{
rating = resarray[0];
average = resarray[1];
total = resarray[2];
}
/* indicate vote was made and show response */
target.innerHTML = "Thank you for voting. You rated this a <strong>" + rating +
"</strong>. There are <strong>" + total + "</strong> total votes. The
average is <strong>" + average + "</strong>. You can see the ratings in the
<a href='http://ajaxref.com/ch2/ratings.txt' target='_blank'>ratings file</a>.";

The complete example can be found at http://ajaxref.com/ch2/twowayimage.html and
the network transmission is shown here to illustrate exactly how data was passed.
Free download pdf