PrototypeAjaxObject
the functions used for doing ajax based page updates
The Ajax object
The Ajax object is a pre-defined object, created by the library to wrap and simplify the tricky code that is involved when writing AJAX functionality. This object serves as the root for many other classes that provide AJAX functionality. This object contains a number of classes that provide encapsulated AJAX logic.
Method | Kind | Arguments | Description |
getTransport() | instance | (none) | Returns a new XMLHttpRequest object |
The Ajax.Base class
This class is used as the base class for the other classes defined in the Ajax object.
Method | Kind | Arguments | Description |
setOptions(options) | instance | options: AJAX options | Sets the desired options for the AJAX operation |
responseIsSuccess() | instance | (none) | Returns true if the AJAX operation succeeded, false otherwise |
responseIsFailure() | instance | (none) | The opposite of responseIsSuccess(). |
The Ajax.Request class
Inherits from Ajax.Base
Encapsulates AJAX operations
Property | Type | Kind | Description |
Events | Array | static | List of possible events/statuses reported during an AJAX operation. The list contains: 'Uninitialized', 'Loading', 'Loaded', 'Interactive', and 'Complete.' |
transport | XMLHttpRequest | instance | The XMLHttpRequest object that carries the AJAX operation |
Method | Kind | Arguments | Description |
ctor(url, options) | constructor | url: the url to be fetched, options: AJAX options | Creates one instance of this object that will call the given url using the given options. Important: It is worth noting that the chosen url is subject to the borwser's security settings. In many cases the browser will not fetch the url if it is not from the same host (domain) as the current page. You should ideally use only local urls to avoid having to configure or restrict the user's browser. (Thanks Clay). |
request(url) | instance | url: url for the AJAX call | This method is typically not called externally. It is already called during the constructor call. |
setRequestHeaders() | instance | (none) | This method is typically not called externally. It is called by the object itself to assemble the HTTP header that will be sent during the HTTP request. |
onStateChange() | instance | (none) | This method is typically not called externally. It is called by the object itself when the AJAX call status changes. |
respondToReadyState(readyState) | instance | readyState: state number (1 to 4) | This method is typically not called externally. It is called by the object itself when the AJAX call status changes. |
The options argument object
An important part of the AJAX operations is the options argument. There's no options class per se. Any object can be passed, as long as it has the expected properties. It is common to create anonymous objects just for the AJAX calls.
Property | Type | Default | Description |
method | String | 'post' | Method of the HTTP request |
parameters | String | The url-formatted list of values passed to the request | |
asynchronous | Boolean | true | Indicates if the AJAX call will be made asynchronously |
postBody | String | undefined | Content passed to in the request's body in case of a HTTP POST |
requestHeaders | Array | undefined | List of HTTP headers to be passed with the request. This list must have an even number of items, any odd item is the name of a custom header, and the following even item is the string value of that header. Example:my-header1', 'this is the value', 'my-other-header', 'another value''>'my-header1', 'this is the value', 'my-other-header', 'another value' |
onXXXXXXXX | Function(XMLHttpRequest) | undefined | Custom function to be called when the respective event/status is reached during the AJAX call. Example var myOpts = {onComplete: showResponse, onLoaded: registerLoaded};. The function used will receive one argument, containing the XMLHttpRequest object that is carrying the AJAX operation. |
onSuccess | Function(XMLHttpRequest) | undefined | Custom function to be called when the AJAX call completes successfully. The function used will receive one argument, containing the XMLHttpRequest object that is carrying the AJAX operation. |
onFailure | Function(XMLHttpRequest) | undefined | Custom function to be called when the AJAX call completes with error. The function used will receive one argument, containing the XMLHttpRequest object that is carrying the AJAX operation. |
insertion | Function(Object, String) | null | Function to be called to inject the returned text into an element. The function will be called with two arguments, the element object to be updated and the response text Applies only to Ajax.Updater objects. |
evalScripts | Boolean | undefined, false | Determines if script blocks will be evaluated when the response arrives. Applies only to Ajax.Updater objects. |
decay | Number | undefined, 1 | Determines the progressive slowdown in a Ajax.PeriodicalUpdater object refresh rate when the received response is the same as the last one. For example, if you use 2, after 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. |
The Ajax.Updater class
Inherits from Ajax.Request
Used when the requested url returns HTML that you want to inject directly in a specific element of your page. You can also use this object when the url returns <script> blocks that will be evaluated upon arrival. Use the evalScripts option to work with scripts.
Property | Type | Kind | Description |
ScriptFragment | String | static | A regular expression to identify scripts |
containers | Object | instance | This object contains two properties: containers.success will be used when the AJAX call succeeds, and containers.failure will be used otherwise. |
Method | Kind | Arguments | Description |
ctor(container, url, options) | constructor | container:this can be the id of an element, the element object itself, or an object with two properties - object.success element (or id) that will be used when the AJAX call succeeds, and object.failure element (or id) that will be used otherwise. url: the url to be fetched, options: AJAX options | Creates one instance of this object that will call the given url using the given options. |
updateContent() | instance | (none) | This method is typically not called externally. It is called by the object itself 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. |
The Ajax.PeriodicalUpdater class
Inherits from Ajax.Base
This 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. Check the Ajax.Updater reference for more information.
Property | Type | Kind | Description |
container | Object | instance | This value will be passed straight to the Ajax.Updater's constructor. |
url | String | instance | This value will be passed straight to the Ajax.Updater's constructor. |
frequency | Number | instance | Interval (not frequency) between refreshes, in seconds. Defaults to 2 seconds. This number will be multiplied by the current decay when invoking theAjax.Updater object |
decay | Number | instance | Keeps the current decay level applied when re-executing the task |
updater | Ajax.Updater | instance | The most recently used Ajax.Updater object |
timer | Object | instance | The JavaScript timer being used to notify the object when it is time for the next refresh. |
Method | Kind | Arguments | Description |
ctor(container, url, options) | constructor | container:this can be the id of an element, the element object itself, or an object with two properties - object.success element (or id) that will be used when the AJAX call succeeds, and object.failure element (or id) that will be used otherwise. url: the url to be fetched, options: AJAX options | Creates one instance of this object that will call the given url using the given options. |
start() | instance | (none) | This method is typically not called externally. It is called by the object itself to start performing its periodical tasks. |
stop() | instance | (none) | This method is typically not called externally. It is called by the object itself to stop performing its periodical tasks. |
updateComplete() | instance | (none) | This method is typically not called externally. It is called by the currently used Ajax.Updater after if completes the request. It is used to schedule the next refresh. |
onTimerEvent() | instance | (none) | This method is typically not called externally. It is called internally when it is time for the next update. |
Use Examples
Using the Ajax.Request class
If you are not using any helper library, you are probably writing a whole lot of code to create a XMLHttpRequest object and then track its progress asynchronously, then extract the response and process it. And consider yourself lucky if you do not have to support more than one
type of browser.
To assist with AJAX functionality, the library defines the Ajax.Request class.
Let's say you have an application that can communicate with the server via the url http://yoursever/app/get_sales?empID=1234&year=1998, which returns an XML response like the following.
<?xml version="1.0" encoding="utf-8" ?>
<ajax-response>
<response type="object" id="productDetails">
<monthly-sales>
<employee-sales>
<employee-id>1234</employee-id>
<year-month>1998-01</year-month>
<sales>$8,115.36</sales>
</employee-sales>
<employee-sales>
<employee-id>1234</employee-id>
<year-month>1998-02</year-month>
<sales>$11,147.51</sales>
</employee-sales>
</monthly-sales>
</response>
</ajax-response>
Talking to the server to retrieve this XML is pretty simple using an Ajax.Request object. The sample below shows how it can be done.
<script>
function searchSales() {
var empID = $F('lstEmployees');
var y = $F('lstYears');
var url = 'http://yoursever/app/get_sales';
var pars = 'empID=' + empID + '&year=' + y;
var myAjax = new Ajax.Request(
url,
{method: 'get', parameters: pars, onComplete: showResponse}
);
}
function showResponse(originalRequest) {
//put returned XML in the textarea
$('result').value = originalRequest.responseText;
}
</script>
<select id="lstEmployees" size="10" onchange="searchSales()">
<option value="5">Buchanan, Steven</option>
<option value="8">Callahan, Laura</option>
<option value="1">Davolio, Nancy</option>
</select>
<select id="lstYears" size="3" onchange="searchSales()">
<option selected="selected" value="1996">1996</option>
<option value="1997">1997</option>
<option value="1998">1998</option>
</select>
<br>
<textarea id=result cols=60 rows=10 ></textarea>
Can you see the second parameter passed to the constructor of the Ajax.Request object? The parameter {method: 'get', parameters: pars, onComplete: showResponse} represents an anonymous object in literal notation. What it means is that we are passing an object that has a property named method that contains the string 'get', another property named parameters that contains the querystring of the HTTP request, and an onComplete property/method containing the function showResponse.
There are a few other properties that you can define and populate in this object, like asynchronous, which can be true or false and determines if the AJAX call to the server will be made asynchronously (the default value is true.)
This parameter defines the options for the AJAX call. In our sample, we are calling the url in the first argument via a HTTP GET command, passing the querystring contained in the variable pars, and the Ajax.Request object will call the showResponse function when it finishes retrieving the response.
As you may know, the XMLHttpRequest reports progress during the HTTP call. This progress can inform four different stages: Loading, Loaded, Interactive, or Complete. You can make the Ajax.Request object call a custom function in any of these stages, the Complete being the most common one. To inform the function to the object, simply provide property/methods named onXXXXX in the request options, just like the onComplete from our example. The function you pass in will be called by the object with one argument, which will be the XMLHttpRequest object itself. You can then use this object to get the returned data and maybe check the status property, which will contain the HTTP result code of the call.
Two other interesting options can be used to process the results. We can specify the onSuccess option as a function to be called when the AJAX call executes without errors and, conversily, the onFailure option can be a function to be called when a server error happens. Just like the onXXXXX option functions, these two will also be called passing the XMLHttpRequest object that carried the AJAX call.
Our sample did not process the XML response in any interesting way. We just dumped the XML in the textarea. A typical usage of the response would probably find the desired information inside the XML and update some page elements, or maybe even some sort of XSLT transformation to produce HTML in the page.
For more complete explanations, see the Ajax.Request reference and the options reference.
Using the Ajax.Updater class
If you have a server endpoint that can return information already formatted in HTML, the library makes life even easier for you with the Ajax.Updater class. With it you just inform which element should be filled with the HTML returned from the AJAX call. An example speaks better that I can write.
<script>
function getHTML() {
var url = 'http://yourserver/app/getSomeHTML';
var pars = 'someParameter=ABC';
var myAjax = new Ajax.Updater('placeholder', url, {method: 'get', parameters: pars});
}
</script>
<input type=button value=GetHtml onclick="getHTML()">
<div id="placeholder"></div>
As you can see, the code is very similar to the previous example, with the exclusion of the onComplete function and the element id being passed in the constructor. Let's change the code a little bit to illustrate how it is possible to handle server errors on the client.
We will add more options to the call, specifying a function to capture error conditions. This is done using the onFailure option. We will also specify that the placeholder only gets populated in case of a successful operation. To achieve this we will change the first parameter from a simple element id to an object with two properties, success (to be used when everything goes OK) and failure (to be used when things go bad.) We will not be using the failure property in our example, just the reportError function in the onFailure option.
<script>
function getHTML() {
var url = 'http://yourserver/app/getSomeHTML';
var pars = 'someParameter=ABC';
var myAjax = new Ajax.Updater(
{success: 'placeholder'},
url,
{method: 'get', parameters: pars, onFailure: reportError}
);
}
function reportError(request) {
alert('Sorry. There was an error.');
}
</script>
<input type=button value=GetHtml onclick="getHTML()">
<div id="placeholder"></div>
If your server logic returns JavaScript code instead of HTML markup, the Ajax.Updater object can evaluate that JavaScript code. To get the object to treat the response as JavaScript, you simply add evalScripts: true; to the list of properties in the last argument of the object constructor.
For more complete explanations, see the Ajax.Updater reference and the options reference.