AJAX - The Complete Reference

(avery) #1

PART II


Chapter 9: Site and Application Architecture with Ajax 425


Automatic Communication Fallback


The last section might have seemed like a trip down JavaScript communication method
memory lane, but there really was an important purpose for it. Our goal was to remind
readers that there are many other ways to communicate to the server so we can add an
alternative communication mechanism in case the XMLHttpRequest object is for some
reason unavailable. To this end, we add to the AjaxTCR library an option fallback.
By default it will be true, but you may override it globally with a call to AjaxTCR.comm
.setDefault("DEFAULT_FALLBACK",false). Also introduced is the fallbackTransport
option, which takes values of "iframe", "image", or "script", which are the same as our
manual transport settings. By default, the fallbackTransport value is "iframe", as it can
support both GET and POST requests. Similarly, a global override could be performed with
AjaxTCR.comm.setDefault("DEFAULT_FALLBACK_TRANSPORT",transport-name),
where you set transport-name to the communications transport type you wish to fall
back to.
The fallback is invoked if for some reason an XHR cannot be created. The library
ensures that if the iframe transport is not used, POST requests are converted to GETs.

/* get xhr here, so if it fails, we can modify content and resend */
if (request.transport == "xhr")
{
request.xhr = AjaxTCR.comm._createXHR();
if (!request.xhr && request.fallback)
{
request.transport = request.fallbackTransport.toLowerCase();
if ((request.transport == "script" || request.transport == "image")
&& request.method.toUpperCase() == "POST")
{
request.method = "GET";
request.url = request.url + "?" + request.postBody;
request.postBody = null;
}
}
else if (!request.xhr)
{ /* raise exception */
}
}

Now, revisiting the server-side program, three general cases must be handled: an XHR
request, an alternate JavaScript request likely using an iframe, and a traditional click-and-
post style response. The server-side code looks at the headers and any query string or
message payload for the X-Requested-By value. Note that by default, these headers and
payload values are sent as indicated by the constant AjaxTCR.comm.DEFAULT_TRANSPORT_
INDICATOR. This can be overridden for a single request by passing in transportIndicator:
false in the options object or for all requests by a call to AjaxTCR.comm.setDefault
("transportIndicator",false). Of course AjaxTCR.comm.setDefault(
"transportIndicator",true) will turn it back on.

$headers = getallheaders();
if (isset($headers["X-Requested-By"]) || isset($headers["x-requested-by"]))
Free download pdf