AJAX - The Complete Reference

(avery) #1

PART II


Chapter 6: Networking Considerations 259


When the user leaves the page, you might determine if the server should be alerted and
what should be sent. If all is well, maybe a simple indication of number of requests made
and an “all clear” flag should be sent. If some intermittent errors happened, those should be
packaged up and sent to the server. The basic idea of this is implemented here, while
leaving room to expand upon. First, a private object, _commResults, which will keep track
of communication statistics, is defined.

/* Collect data across all requests */
_commResults : {
totalRequests : 0,
totalTimeouts : 0,
totalRetries : 0,
totalSuccesses : 0,
totalFails : 0,
requestFails : new Array()},

Notice in the fragment that an array for requestFails is defined. This will store a bit
more detail on those requests that fail since those will be the ones you are most interested
in. Now, as requests are made, the library updates the various values. For example, in
_handleFail(),not only is the callback called and data cleaned up, but statistics and
details about the failure are recorded.

_handleFail : function(response, message) {
/* Increment total fails */
AjaxTCR.comm.stats._commResults.totalFails++;
/* Save fail details */
var fail = {};
fail.url = response.url;
fail.status = response.xhr.status;
fail.message = message;
AjaxTCR.comm.stats._commResults.requestFails.push(fail);

response.onFail(response, message);
}

Note that we omit the other parts of the code that also update the various counters in
_commResults.
To enable connection statistics tracking, call the public method AjaxTCR.comm.stats
.collect(url) and pass the URL you are interested in sending the data to. The information
will be sent in a JSON structure when the page is unloaded.

collect : function (url) {
var sendConnectionStats = function(){
var results = AjaxTCR.comm.stats.get();
if (results.totalRequests > 0)
{
var payload = AjaxTCR.data.encodeJSON(results);
AjaxTCR.comm.sendRequest(url, {method:"POST",
payload:payload,
requestContentType:"application/json",
oneway:true});
}
Free download pdf