Ajax.Updater

new Ajax.Updater(container, url[, options])

 

Performs an AJAX request and updates a container’s contents based on the response text.

 

Ajax.Updater is a specialization of Ajax.Request: everything about the latter is true for the former. If you’re unfamiliar with Ajax.Request, go read its documentation before going ahead with this one.

 

A simple example

 

new Ajax.Updater('items''/items', {

  parameters: { text: $F('text') }

});

 

A note about timing

 

The onComplete callback will get invoked after the update takes place.

 

Additional options

 

Since the goal of Ajax.Updater is specifically to update the contents of a DOM element (container) with the response text brought back by the AJAX request, it features a couple of new options, in addition to the common options set. These are:

 

Option

Default

Description

evalScripts

false

This determines whether <script> elements in the response text are left in (and therefore evaluated by the browser) or not.

insertion

None

By default, Element.update is used, which replaces the whole contents of the container with the response text. You may want to instead insert the response text around existing contents. You just need to pass a valid Insertion object for this, such as Insertion.Bottom.

 

In the following example, we assume that creating a new item through AJAX returns an XHTML fragment representing only the new item, which we need to add within our list container, but at the bottom of its existing contents. Here it goes:

 

new Ajax.Updater('items''/items', {

  parameters: { text: $F('text') },

  insertion: Insertion.Bottom

});

 

 

Single container, or success/failure alternative?

 

The examples above all assume you’re going to update the same container whether your request succeeds or fails. There may very well be times when you don’t want that. You may want to update only for successful requests, or update a different container on failed requests.

 

To achieve this, you can pass an object instead of a DOM element for the container parameter. This object must exhibit a success property, whose value is the container to be updated upon successful requests. If you also provide it with a failure property, its value will be used as the container for failed requests.

 

In the following code, only successful requests get an update:

 

new Ajax.Updater({ success: 'items' }, '/items', {

  parameters: { text: $F('text') },

  insertion: Insertion.Bottom

});

 

The next example assumes failed requests will feature an error message as response text, and will go on to update another element with it, probably a status zone.

 

new Ajax.Updater({ success: 'items', failure: 'notice' }, '/items', {

  parameters: { text: $F('text') },

  insertion: Insertion.Bottom

});

 

 


Prototype API 1.5.0 - prototypejs.org