AJAX - The Complete Reference

(avery) #1

PART III


Chapter 10: Web Services and Beyond 519


a great number of network requests for very little value. You might consider adding a decay
concept to a polling solution, the idea being that if you do not see changes, you increase the
delay between poll attempts. However, a downside to this approach is that when such
infrequent changes do happen, it may be some time before the user is altered to them.
The long poll pattern is better for dealing with updates that may not be predictable.
Connections are re-established upon data or can be set to re-establish upon a timeout with a
retry mechanism. The following example (http://ajaxref.com/ch10/longpoll.html) uses this
pattern to call a server-side program that responds with a varying amount of time. If the
server doesn’t respond in 30 seconds, it will retry again for a total of 10 times, assuming a
three-minute period of inactivity indicating the server being unavailable. However, if the
server does respond, you’ll note that outputTarget gets updated, but the onSuccess
handler just starts the request all over again.

<!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 10 - Long Poll</title>
<script src="http://ajaxref.com/ch10/ajaxtcr.js" type="text/javascript"></script>
<script type="text/javascript">
function sendRequest(response)
{
var options = {method: "GET",
outputTarget: "hellodiv",
retries: 10,
timeout: 30000,
onSuccess: sendRequest};

/* treat the first response specially - no delay */
if (!response)
options.payload = "delay=0";
AjaxTCR.comm.sendRequest("http://ajaxref.com/ch10/longpoll.php", options);
}
AjaxTCR.util.event.addWindowLoadEvent(function(){sendRequest(false);});
</script>
</head>
<body>
<h1>Long Poll</h1>
<div id="hellodiv"></div>
</body>
</html>

The simple PHP code to simulate a long poll pattern just creates random delays to give
a sense of intermittent server activity.

<?php
header("Cache-Control: no-cache");
header("Pragma: no-cache");
if ($_GET["delay"])
$delay =$_GET["delay"];
else
Free download pdf