AJAX - The Complete Reference

(avery) #1

426 Part II: Developing an Ajax Library^


$transport = "XHR";
else if (gpc("X-Requested-By") != "")
$transport = htmlentities(substr(urldecode(gpc("X-Requested-By")),0,1024));
else
$transport = "downgrade";

In case someone is tampering with headers or request payload and sending unknown
values, we simply assume the result to be using a downgrade transport. Now after
determining the transport, the server-side script outputs the results accordingly.

/* set the cache control headers */
header("Cache-Control: no-cache");
header("Pragma: no-cache");
if (($transport == "XHR") || $transport == "iframe" || $transport == "downgrade")
{
$message = "<span id='pollResults'>Thank you for voting. You rated this a
<strong>$rating</strong>. There are <strong>$votes</strong> total votes.
The average is <strong>$average</strong>. You can see the ratings in the
<a href='http://ajaxref.com/ch9/ratings.txt' target='_blank'>ratings file</a>
</span>";
}
else if ($transport == "HTMLScriptTag")
{
header("Content-Type: application/x-javascript");
if (gpc("callbackfunction") != "")
$message = gpc("callbackfunction"). "($rating, $votes, $average);";
}
else if ($transport == "image")
{
$results = $rating. "_". $votes. "_". $average;
/* send an image back */
$filename = 'pixel.gif';
$fp = fopen($filename, 'rb');
header("Content-Type: image/gif");
header("Content-Length: ". filesize($filename));
/* set the cookie with the result */
setcookie("PollResults", $results, time()+3600, "/", "ajaxref.com");
/* dump the response image and end the script */
fpassthru($fp);
exit;
}
/* now just dump out the simple HTML fragment for XHR or iframe */
if ($transport != "downgrade")
{
echo $message;
exit;
}
/* otherwise dump out the whole file */
?>
<!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=UTF-8" />
Free download pdf