AJAX - The Complete Reference

(avery) #1

PART II


Chapter 9: Site and Application Architecture with Ajax 433


/* send response */
/* first send the right headers */
header("Cache-Control: no-cache");
header("Pragma: no-cache");
require('../lib/Smarty/Smarty.class.php');
$smarty = new Smarty();
$smarty->template_dir = './templates';
$smarty->compile_dir = './templates/templates_c';
$smarty->cache_dir = './templates/cache';
$smarty->config_dir = './templates/config';
if ($transport == 'downgrade')
$smarty->assign('downgradeversion', true);
$smarty->assign('rating', $rating);
$smarty->assign('votes', $votes);
$smarty->assign('average', $average);
$smarty->display('ratingResponse.tpl');

Now the server-side code is a bit cleaner and it should work similar to the previous
versions. You even might wonder what the value is of using a template system like Smarty
here, and honestly, there isn’t much. We could have created a similar mechanism in raw
PHP, JSP, or other server-side script environment. However, that will change shortly.
It seems like we haven’t gained much so far, since the server is still sending prerendered
content as a response even when Ajax is on. That’s quite true and it could hurt the performance
of the application, depending on the size of the markup versus content and how frequently it
is sent. It would be more desirable to send down only the data packet:

{"average":3.37,"rating":"4","votes":475}

and then on the client side, store some portion of the template and populate it locally. We’ll
see shortly that we can indeed render the template locally, but obviously given the last
example, it will be inefficient to send the header and footer markup that won’t be needed if
only a portion of the page is being rendered. A better template to address the variable need
for the extra markup would be something like so:

{if $downgradeversion}
{include file="ratingHeader.tpl"}
{/if}
<h3>Thanks for voting!</h3>
<p>Your rating: {$rating}. <br />
Average rating: {$average}.<br />
Total votes: {$votes}. <br />
</p>
{if $downgradeversion}
{include file="ratingFooter.tpl"}
{/if}

where ratingHeader.tpl just had the following markup in it:

<!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