AJAX - The Complete Reference

(avery) #1

PART II


Chapter 5: Developing an Ajax Library 215


As the first introduction, we’ll once again implement a basic “Hello Ajax World”
example. In the case of Prototype, define the sendRequest() function like so:

function sendRequest()
{
new Ajax.Request("http://ajaxref.com/ch1/sayhello.php",
{method:"GET", onSuccess: handleResponse});
}

Now the callback function will be invoked upon a successful response and will pass
back a reference to the XHR object currently being serviced:

function handleResponse(response)
{
var msg =
response.responseXML.getElementsByTagName("message")[0].firstChild.nodeValue;
$("responseOutput").update(msg);
}

Callback Description
onCreate Triggered after the Ajax.Request object is initialized but before the
XHR is really used.
onComplete Triggered at the end of the request after all other callbacks like onSuccess
and onStatuscode and any automatic behaviors are invoked.
onException Triggered when an XHR error occurs. The callback function will receive
the Ajax.Requester instance as the first parameter and an exception
object as the second. Exceptions can be raised for basic failures of XHR
creation or use as well as for some problems with responses such as
status code access errors or some JSON decode issues.
onFailure Invoked when a request has returned, but it is not a 200-range response.
If there is a particular handler for the response code like on404, this
callback will not be sent.
onInteractive Corresponds to readyState 3 values that var y in terms of what can be
used by browsers.
onLoaded Invoked just after the XHR being sent and reaching a readyState of 2.
onLoading Invoked after XHR has been set up and the open() method called as
indicated by a readyState value of 1.
onStatuscode
(on404,on500, etc.)

You can set unique handlers for each status code you are interested in
and if the response invokes one of these callbacks it will then not use
onFailure or onSuccess. However, onComplete will be called.
onSuccess Invoked when a request is received and the status code is in the 200
range. It may be skipped in the case a corresponding on200 or other
status-specific callback is set.
onUninitialized Invoked just after the XHR was created but the open() method has not
been called. This would correspond to readyState 0.

TABLE 5-8 Prototype 1.5.1.1 Callbacks
Free download pdf