AJAX - The Complete Reference

(avery) #1

PART II


Chapter 9: Site and Application Architecture with Ajax 447


<!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>Chapter 9 : Architecture - In Page Ajax - Tag Based Widget</title>
<AjaxTCR:includeLib>
</head>
<body>
<AjaxTCR:widget name="rating" question="How do you feel about widgets?" max="5"
maxstring="Love them!" min="1" minstring="Blech"
url="rate.php" payloadvalue="rating" />
</body>
</html>

Of course, that is just the template file itself and it tends to look a bit too simple. The file
that replaces the tags with the code isn’t exactly a small bit of work. Fortunately, in many
environments, the ability to define custom tags is built in. We show the code here only as
demonstration so you can see that all it is doing is swapping out attribute names and
building the script code and HTML markup that makes up the widget. Look at the functions
createRatingWidget and addScript to see this.

<?php
ob_start("translateOutput");

function translateOutput($output)
{
/* Search for AjaxTCR:widget tags */
$ratingItems = array();
preg_match_all('/\<AjaxTCR:widget([^>]*)\/>/is', $output, $matches,
PREG_SET_ORDER);
for ($i=0; $i < count($matches); $i++)
{
$widgetTag = $matches[$i][0];
$allAttributes = $matches[$i][1];
$newOutput = $attributes;
preg_match_all('/\s*(\w+)\s*=\s*[\'\"]([^\'\"]+)[\'\"]/is',
$allAttributes, $attMatches, PREG_SET_ORDER);
$attributes = array();

for($j=0;$j<count($attMatches);$j++)
$attributes[$attMatches[$j][1]] = $attMatches[$j][2];
$attributes["id"] = $i;
array_push($ratingItems, $i);
if (strtolower($attributes["name"]) == "rating")
$newOutput = createRatingWidget($attributes);
// Replace with actual HTML
$output = str_replace($widgetTag, $newOutput, $output);
}

/* Search for AjaxTCR:includeLib tag */
preg_match_all('/\<AjaxTCR:includeLib([^>]*)>/is', $output, $matches,
PREG_SET_ORDER);
Free download pdf