{maketoc}
!The Ajax object

The utility functions mentioned above are nice but, let's face it, they are not the most advanced type of thing, now are they? You could probably have done it yourself and you may even have similar functions in you own scripts. But those functions are just the tip of the iceberg.

I'm sure that your interest in prototype.js is driven mostly by its [http://en.wikipedia.org/wiki/Ajax_%28programming%29|AJAX] capabilities. So let's explain how the library makes your life easier when you need to perform AJAX logic.

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 contains a number of classes that provide encapsulated AJAX logic. Let's take a look at some of them.

!!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.

{code}
<?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>
{/code}

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.

{code source=JavaScript}
<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>
{/code}

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|Ajax.Request reference] and the [#Ajax.options|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.

{code source=JavaScript}
<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>
{/code}

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.

{code source=JavaScript}
<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>
{/code}

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|Ajax.Updater reference] and the [#Ajax.options|options reference].
Page History
Date/CommentUserIPVersion
23 Dec 2005 (20:06 UTC)
Will68.174.96.1014
Current • Source
Will68.174.96.1013
View • Compare • Difference • Source
xing194.152.164.452
View • Compare • Difference • Source