AJAX - The Complete Reference

(avery) #1

432 Part II: Developing an Ajax Library^


To start to move away from this thinking, consider that even in the server-side focused
model, we could take a template like:

<h3>Thanks for voting!</h3>
<p>Your rating: {$rating}. <br />
Average rating: {$average}.<br />
Total votes: {$votes}. <br />
</p>

and then replace the tokens with the actual values of interest. This would be a version that
was appropriate if the request was Ajax, but we would need to include other content if the
request was a downgrade version. We might consider a template that would look
something like:

{if $downgradeversion}
<!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" />
<title>Voting Results for downgraded version</title>
</head>
<body>
<h3>Downgrade Version</h3>
{/if}
<h3>Thanks for voting!</h3>
<p>Your rating: {$rating}. <br />
Average rating: {$average}.<br />
Total votes: {$votes}. <br />
</p>
{if $downgradeversion}
</body>
</html>
{/if}

The idea in the server-side program would be that it would first read the transport type
from the headers, query string, or POST body.

/* read transport type */
$headers = getallheaders();
if (isset($headers["X-Requested-By"]) || isset($headers["x-requested-by"]))
$transport = "XHR";
else if (gpc("X-Requested-By") != "")
$transport = htmlentities(substr(urldecode(gpc
("X-Requested-By")),0,1024));
else
$transport = "downgrade";

It then would perform the normal calculations, but when it is ready to output the response,
it would populate various template values depending on the value in $transport. The syntax
of the popular PHP template engine Smarty (http://smarty.php.net) is used here as a
demonstration:
Free download pdf