AJAX - The Complete Reference

(avery) #1

204 Part II: Applied Ajax^


In this case, handleResponse would be the callback function that will receive an object
containing the familiar responseXML, responseText, and other properties.
The callback function also defines a member failure, which should be associated with
a function to be called upon a failure either in server-response or network timeout.

function handleFailure(response) { alert("So sorry an error has occurred!" );}

var callback = { success: handleResponse,
failure: handleFailure };

To control the indication of failure, it is possible to set the timeout property for the
callback object to the number of milliseconds to wait before aborting the request and invoking
any defined failure callback.

var callback = { success: handleResponse,
failure: handleFailure,
timeout: 5000 /* timeout in 5 seconds */
};

A callback function specifically to be invoked in the case file upload is used can be
defined by setting the upload member of the callback object. However, as mentioned in
previous chapters, XHRs are not employed in file uploads; instead, iframes are employed,
so there may be very different capabilities in terms of controlling the connection. A callback
for file uploads is not required if a silent transfer is preferred.

var callback = { upload: handleUploadResponse };

The final members of YUI’s callback object are argument and scope. The argument
value can be set to a legal JavaScript type value such as string, number, Boolean, array, or
object that contains any values you may wish to pass to the callback functions associated
with success or failure.

var callback = { success: handleResponse,
failure: handleFailure,
timeout: 5000, /* timeout in 5 seconds */
argument: {username: "thomas" , dog: "Angus" , example: true}
};

You should note that the values placed in the argument property are not sent during
any communication; the property is used solely as a convenient way to pass data around
without explicit creation of closures. Then in the various callback functions, the argument
can be accessed as part of the returned response object.

function handleResponse(response)
{
var name = response.argument.username;
var dog = response.argument.dog;
var example = response.argument.example;

/* do something interesting */
}
Free download pdf