Section 10.1. Ajax Support


10.1. Ajax Support

In this section, we'll look at the three main classes that see most of the action in Prototype's Ajax code: Ajax.Request, Ajax.Updater, and Ajax.PeriodicalUpdaterall of which inherit from Ajax.Base. After that is the Ajax.Responders object, which handles global events related to Ajax calls.

10.1.1. Base Objects

The Ajax object serves as the root and namespace for Prototype's classes and methods that provide Ajax functionality:


activeRequestCount

The number of Ajax requests in progress


getTransport( )

Returns a new XMLHttpRequest object

Ajax.Base is used as the base class for other classes defined in the Ajax object. As such, these methods are available in Ajax.Request, Ajax.Updater, and Ajax.PeriodicalUpdater objects.


setOptions( options )

Sets the desired options for the Ajax operation. See "Ajax.Request options" later in this chapter.


responseIsSuccess( )

TRue if the Ajax operation succeeded, and false otherwise.


responseIsFailure( )

false if the Ajax operation succeeded, and TRue otherwise.

10.1.2. Ajax Requests

The Ajax.Request class (which inherits from Ajax.Base) encapsulates Ajax operations.


initialize( url , options )

Creates one instance of this object that will create an XMLHttpRequest object for the given url, using the given options (which may include callbacks to handle the response; see the upcoming section "Ajax.Request options"). The onCreate event will be raised during the constructor call. Generally, only URLs from the same domain as the current page are allowed to be retrieved; see the discussion of "The Same-Origin Policy" in Chapter 8.


request( url )

Called by the constructor; not typically called externally.


evalJSON( )

Evaluates the content of an eventual X-JSON HTTP header present in the Ajax response. Not typically called externally.


evalResponse( )

Evaluates the response body as JavaScript. Called internally if the response has a Content-type header of text/javascript. Not typically called externally.


header( name )

Retrieves the contents of the HTTP header named name from the response (only available after the Ajax call is completed).


onStateChange( )

Called internally when the readyState changes. See Table 10-2. Not typically called externally.


respondToReadyState( readyState )

Called by the object when the readyState changes. See Table 10-1. Not typically called externally.


setRequestHeaders( )

Assembles the HTTP header that will be sent during the HTTP request. Not typically called externally.


Events

An array of possible events/statuses reported during an Ajax operation. The list contains: Uninitialized, Loading, Loaded, Interactive, and Complete.


transport

The XMLHttpRequest object that carries the Ajax operation.


url

The URL targeted by the request.

10.1.2.1. Ajax.Request options

The options argument is an anonymous JavaScript object in literal notation. Any object can be passed as long as it has the expected properties, but it's common to create anonymous objects just for the Ajax calls (see Table 10-1).

Table 10-1. Ajax operations
PropertyDescription
method

A string with the HTTP method for the request. Defaults to post.
parameters

A object (like {pet:'monkey'}) or URL-formatted string (like "pet=monkey") with the list of values passed to the request. Defaults to empty.
encoding

A string representing the encoding of a request body. Defaults to UTF-8.
username

A string with the username to be used for HTTP authentication.
password

A string with the password to be used for HTTP authentication.
asynchronous

A Boolean indicating whether the Ajax call will be made asynchronously. Defaults to true.
contentType

A string specifying the Content-Type header that will be sent with the HTTP request. Defaults to application/x-www-form-urlencoded.
postBody

A string with the content passed to in the request's body in case of a HTTP POST or PUT. Defaults to undefined.
requestHeaders

A collection of HTTP headers to be passed with the request. Either an object (like {foo-header:'value 1', bar-header:'value 2'}) or an array with an even number of items (like ['foo-header', 'value 1', 'bar-header', 'value 2']). Defaults to undefined.
onLoading

Callback function to be called when the request's readyState reaches 1 (see Table 10-2). The function will receive two arguments: the XMLHttpRequest request object, and the evaluated X-JSON response HTTP header.
onLoaded

Callback function to be called when the request's readyState reaches 2 (see Table 10-2). The function will receive two arguments: the XMLHttpRequest request object, and the evaluated X-JSON response HTTP header.
onInteractive

Callback function to be called when the request's readyState reaches 3 (see Table 10-2). The function will receive two arguments: the XMLHttpRequest request object, and the evaluated X-JSON response HTTP header.
onComplete

Callback function to be called when the request's readyState reaches 4 (see Table 10-2). The function will receive two arguments: the XMLHttpRequest request object, and the evaluated X-JSON response HTTP header.
onSuccess

Callback function to be called when the request's readyState reaches 4 and the HTTP response status is in the 200 range. The function will receive two arguments: the XMLHttpRequest request object and the evaluated X-JSON response HTTP header.
onFailure

Callback function to be called when the request's readyState reaches 4 and the HTTP response status is not in the 200 range. The function will receive two arguments: the XMLHttpRequest request object and the evaluated X-JSON response HTTP header.
onException

Callback function to be called when an exceptional condition happens on the client side of the Ajax call, such as an invalid response or invalid arguments. The function will receive two arguments: the Ajax.Request request object and the exception object.


In addition to the callbacks available for the general response conditions (onSuccess, onFailure, etc.), callbacks can be created for specific HTTP response codes (404, 500, and so on) as well. See below for an example.

10.1.2.2. Examples

Create an Ajax request for a remote file, with options to specify the HTTP request method, and a callback to handle the response:

new Ajax.Request('/data.html', {   method: 'get',   onComplete: showResponse }); // alert the returned value function showResponse(request) {   alert(request.responseText); }

The callback could also be defined inline. For example, this is equivalent to the previous example (see Table 10-2):

new Ajax.Request(' /data.xml', {   method: 'get',   onComplete: function(request){ alert(request.responseText); } });

Callbacks can be defined for specific HTTP response codes, as well:

new Ajax.Request(' /data.xml', {   method: 'get',   on404: function(request){ alert('Not found'); },   on500: function(request){ alert('Server error'); } });

Table 10-2. XMLHttpRequest readyState properties
readyStateDescriptionPrototype callback
 Request object has not yet been created. 
0 (Uninitialized)Request object's open( ) method has not yet been called. 
1 (Loading)Request object's send( ) method has not yet been called.
onLoading

2 (Loaded)The request has been initiated.
onLoaded

3 (Interactive)The response is being received.
onInteractive

 The response is ready and its status is in the 200 range.
onSuccess

 The response is ready and its status is not in the 200 range.
onFailure

4 (Complete)The response is ready.
onComplete


10.1.3. Ajax Updaters

The Ajax.Updater class (which inherits from Ajax.Request) is used when the requested URL returns content that you want to inject directly in a specific element of your page.


initialize( container , url , options )

Creates an Ajax.Updater instance that will call url using the given options. The container argument can be the ID of an element, the element object itself, or an object with either or both of two properties: success, which is an element or ID that will be updated when the Ajax call succeeds, and failure, which is the element (or ID) that will be updated otherwise. The options argument provides the same options as Ajax.Request (see "Ajax.Request options," earlier in this chapter) and some options particular to updaters (see "Ajax.Updater options," next).


updateContent( )

Called internally when the response is received. It will update the appropriate element with the HTML or call the function passed in the insertion option. The function will be called with two arguments: the element to be updated and the response text. Not typically called externally.


containers

Contains two properties: success, which is the element to be updated when the request succeeds, and failure, which is the element to be updated otherwise.

10.1.3.1. Ajax.Updater options

In addition to the options described in the section "Ajax.Request options," Ajax.Updater classes can also take these options:

insertion

An Insertion class that will determine how the new content will be inserted. It can be Insertion.Before, Insertion.Top, Insertion.Bottom, or Insertion.After (see "Inserting Content"). Defaults to undefined.
evalScripts

A Boolean that determines whether <script> blocks will be evaluated when the response arrives, instead of inserted into the page. Defaults to undefined (false).


10.1.3.2. Examples

Replace the contents of a DIV with the contents of a remote file:

// <div >(To be replaced)</div> new Ajax.Updater('target', '/data.html', {method: 'get'});

This next example is the same as above, but it updates the element only if the request was successful and alerts the user if not:

// <div ></div> new Ajax.Updater({success: 'target'}, '/data.html', {   method: 'get',    onFailure: function(request) { alert('Sorry. There was an error.') } });

10.1.4. Periodical Ajax Updaters

The Ajax.PeriodicalUpdater class repeatedly instantiates and uses an Ajax.Updater object to refresh an element on the page or to perform any of the other tasks the Ajax.Updater can perform.


initialize( container , url , options )

Creates an instance that will update container with the result of a request to url. container can be the id of an element, the element object itself, or an object with one or both of two properties: success, which is an element (or id) that will be updated when the request succeeds, and failure, which is an element (or id) that will be updated otherwise. The available properties of the options argument are detailed in the section below "Ajax.PeriodicalUpdater options."


start( )

Start performing the periodical tasks. Not typically called externally.


stop( )

Stop performing the periodical tasks. After stopping, the object will call the callback given in the onComplete option (if any).


updateComplete( )

Schedules the next refresh; called by the currently used Ajax.Updater after it completes the request. Not typically called externally.


onTimerEvent( )

Called internally when it is time for the next update. Not typically called externally.


container

An object that will be passed straight to the Ajax.Updater's constructor.


url

A string that will be passed straight to the Ajax.Updater's constructor.


frequency

Interval (not frequency) between refreshes, in seconds. Defaults to 2 seconds. This number will be multiplied by the current decay when invoking the Ajax.Updater object.


decay

A number that keeps the current decay level applied when re-executing the task.


updater

The most recently used Ajax.Updater object.


timer

The JavaScript timer being used to notify the object when it is time for the next refresh.

10.1.4.1. Ajax.PeriodicalUpdater options

In addition to the options described in the earlier sections "Ajax.Request options" and "Ajax.Updater options," Ajax.PeriodicalUpdater can also take these options:

decay

A number determining the progressive slowdown in an Ajax.PeriodicalUpdater object refresh rate when the received response is the same as the last one. For example, if the rate is 2 and one of the refreshes produces the same result as the previous one, the object will wait twice as much time for the next refresh. If it repeats again, the object will wait four times as much, and so on. Leave it undefined or use 1 to avoid the slowdown.
frequency

Interval (not frequency) between refreshes, in seconds. Applies only to Ajax.PeriodicalUpdater objects. Defaults to 2.


10.1.4.2. Example
// <div ></div> new Ajax.PeriodicalUpdater('target', '/data.html', {   method: 'get',    frequency: 2 });

10.1.5. Global Responders

The Ajax.Responders object maintains a list of callbacks that will be called when Ajax-related events occur, regardless of what object created them; for example, creating a global exception handler for Ajax operations. If you have code that should always be executed for a particular event, regardless of which Ajax call caused it to happen, then you can use the Ajax.Responders object.


register( responderToAdd )

The object passed in the responderToAdd argument should contain methods named like the Ajax events (e.g., onCreate, onComplete, onException). When the corresponding event occurs, all the registered objects that contain a method with the appropriate name will have that method called.


unregister( responderToRemove )

The object passed in the responderToRemove argument will be removed from the list of registered objects.


dispatch( callback , request , transport , json )

Runs through the list of registered objects looking for the ones that have the method determined in callback. Then each of these methods is called passing request, transport, and json. If the Ajax response contains an X-JSON HTTP header with some JSON content, then it will be evaluated and passed in the json argument. If the event is onException, the transport argument will have the exception instead and json will not be passed.


responders

An array of objects registered for Ajax events notifications.

In addition to the methods listed here, Ajax.Responders is also extended by the Enumerable methods.

10.1.5.1. Example

Suppose you want to show some visual indication that an Ajax call is in progress, such as a spinning icon. You can use two global event handlers to help you, one to show the icon when the first call starts and another one to hide the icon when the last one finishes.

// <img src="/books/4/386/1/html/2/spinner.gif"  style="display: none"> Ajax.Responders.register({   onCreate: function(  ){     $('spinner').show(  );   },   onComplete: function(  ) {     if(Ajax.activeRequestCount == 0)       $('spinner').hide(  );   } });




Ajax on Rails
Ajax on Rails
ISBN: 0596527446
EAN: 2147483647
Year: 2006
Pages: 103
Authors: Scott Raymond

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net