Updating your page dynamically with Ajax.Updater – Prototype API


Well most of web devs desire Ajax to update parts of the document by receiving HTML fragments. If I assume right that you are one of them then this one is for you. Also we are going to approach below in Prototype.js way 🙂

By the way, Are you a jQuery lover? If yes, then you should know jQuery(1.4.x) doesn’t provide such facility directly  😉

Normally in prototype.js – ajax, we execute Ajax.Request(Click here in case ur not familiar with it) to make our asynchronous requests.

In order to update part of your HTML document with HTML fragments, with Ajax.Request with an onComplete callback this is fairly easy, but with Ajax.Updater it’s even easier! 😀

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

Lets have some real example below:

Suppose you have such a portion in your HTML document

<h2>List of My Girlfriends </h2>
<!-- By the way, how many GF do you have? -->
<div id="girlfriends">(fetching girlfriends list ...)</div>

And you are suppose to fill that “girlfriends” DIV with…

new Ajax.Updater('girlfriends', 'gfManager.php', { method: 'get' });

That’s all. 🙂 No hassle… It will update your “girlfriends” DIV with girlfriends name list.

And your server end script responded well and looks like below:

<h2>List of My Girlfriends </h2>
<div id="girlfriends">
<li> Emma Watson </li>
<li> Nora Ali </li>
<li> Jessica Parker </li>

The arguments are the same of Ajax.Request, except there is the receiver element in the first place. Prototype will automagically update the container with the response using the Element.update() method.

And if you are smart enough you can implement this one in your own way.

Here i built my own username availability checker at some user signup page:

<label for="username">username:</label>
<input type="text" name="username" id="username" onkeyup="checkUserName();" />
<div id="availability"></div>

with this checkUserName method

function checkUserName() {
 if($F('username').length == 5) {
 var url = 'chkusername.php';
 var params = 'username=' + $F('username');
 var ajax = new Ajax.Updater(
 {success: 'availability'},
 {method: 'get', parameters: params, onFailure: reportError});
function reportError(request) {
 $F('availability') = "Error";

The server end script does query the database and responds whether the username taken or not.
Which looks like below:

If the username is available

If the username is already taken

Cheers! 😀