AJAX - The Complete Reference

(avery) #1

PART II


Chapter 9: Site and Application Architecture with Ajax 417


note earlier the inclusion of a hidden form field with a <noscript> tag that would be sent
in the case JavaScript was off. If script is running, this field wouldn’t be sent and instead an
XHR request is made. Information is added to the request for the server side to understand
how the request was made. The AjaxTCR library does this by setting a request header X-
Requested-By to a value of XHR every time a request is sent. Both the header and default
value can be overridden; you can see how they are employed in the library here:

request.xhr.setRequestHeader(AjaxTCR.comm.DEFAULT_TRANSPORT_HEADER
AjaxTCR.comm.DEFAULT_XHR_TRANSPORT_VALUE);

The server side could certainly look for this header to determine if the request was made
by an XHR or not and decide how to respond. For example, in the server-side program, there
could be something like:

/* omitting the read of data and the rating recording */

/* form the core response */
$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>";

/* get the headers */
$headers = getallheaders();
/* if Ajax header set just send back snippet of content */
if (isset($headers["X-Requested-By"]) && ($headers["X-Requested-By"] == "XHR"))
{
/* output headers */
header("Cache-Control: no-cache");
header("Pragma: no-cache");
echo $message;
exit();
}
/* otherwise output downgrade version */
?>
<!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>If you are not using JavaScript, you will see this downgraded page with
results</h3>
<?php echo $message ?>
</body>
</html>

Figure 9-2 shows that after implementing this approach, a rich Ajax rating can be
provided to those with Ajax enabled and a basic one to those with no script.
Free download pdf