Prototype.js is a library of JavaScript objects and functions, designed to help you code easier. It is particularly useful for Ajax development, as it contains a number of objects that handle Ajax communication, previously requiring lengthy amounts of code.

To begin taking advantage of Prototype.js, download the latest version, save it to a file called prototype.js and import it into your HTML page via:

<script type="text/javascript" src="prototype.js"></script>

The Ajax functionality revolves around the use of three main objects of the Ajax class, namely, Ajax.Request, Ajax.Updater and Ajax.Responders.

Ajax.Request

Ajax.Request object encapsulates the commonly used Ajax code for setting up the XMLHttpRequest object, performing cross-browser checking for compatibility and callback handling.

The example code below will check if an entered username is available or taken.

Firstly, a username is to be entered into a text field:


<body>
	<form>
    Please enter a username:
    <input type="text" id="username" onchange="checkAvailability()" />
	</form>
</body>
</html>

The element id is assigned, so that JavaScript can refer to it later. The onchange event will trigger the checkAvailability () function which is described below.


var url = "checkAvailability.php"; 
 
function checkAvailability() {
  new Ajax.Request(url, {
      method: 'get',
      parameters: { username: document.getElementById('username').value },
      onSuccess: process,
      onFailure: function() { 
      alert("There was an error with the connection"); 
    }
  });
}

The function initialises an Ajax.Request object to handle the request. Notice, that in the URL variable, the server-side script is supplied, which will be explained later. The Ajax.Request is getting two parameters passed to it; the URL of the script and an object that has the parameters for the AJAX call. These parameters are the method, the callbacks, and the username to be sent to the script. The process function is passed to the onSucess callback. The onFailure callback will alert the user if an error had occurred while connecting to the server. The process function is shown below.


function process(transport) {
  var response = transport.responseText;
  if(response == 'available')
    alert("This username is available");
  else
    alert("This username is already registered, please choose another");  
}

The response from the server is stored in the responseText property. In this case the server will return "available" or "unavailable" and the user will be notified accordingly.

The server-side script, checkAvailability.php is needed to check if the username is already taken. For the sake of simplicity of this example an array will hold the usernames that are taken.


<?php
  $usernames = array('neb', 'lkovacev10', 'emuns','ena5','dado17','lara', 'amela12', 'zozo');

  if(in_array($_GET['username'], $usernames))
  	echo 'unavailable';
  else
    echo 'available';
?>

Ajax.Updater

Ajax.Updater is an extension of the Ajax.Request object in that it performs an Ajax request and also updates the page with the returned information.

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

As you can see, it takes three parameters instead of two, with the additional parameter being the container or the location in the HTML page where the returned information should be displayed. In the example below, when a user clicks a button the contents of a <div> element are filled with different types of fruit.


<body>
  <div id="saladContainer">Empty </div>
  <button onclick="fruitSalad()">Fill it with fruit </button>
</body>

The code for the fruitSalad () function is displayed below. An Ajax.Updater object is created and passed three parameters; the id of the <div> element, the destination URL and a method, in this case "get".


function fruitSalad () {
  new Ajax.Updater('saladContainer', 'fruit.php', { method: 'get' });

}

Next, fruit.php script needs to be created to execute the code of retrieving different types of fruit from an array.


<?php
$fruits = array('oranges', 'bananas', 'grapes', 'strawberries', 'watermelon', 'apples'); 

for($i = 0; $i < sizeof($fruits); $i++)
  echo $fruits[$i] . "<br />";
?>

Additionally, Ajax.PeriodicalUpdater can be used to update the content at regular intervals while the response from the server remains unaltered. To do this, use the frequency attribute to set the number of seconds after which the content is to be updated. For instance, frequency: 5, means that the content will be updated every five seconds.

Ajax.Responders

Responders are global objects that monitor all Ajax activity on the page and get notified of each step in the communication process. To register one of these "listeners" use the code below:

Ajax.Responders.register(responder)

You can similarly, unregister them when they are no longer required using:

Ajax.Responders.unregister(responder)

For instance, let's say while the requests are processing we want to show a "processing" icon and hide it when the requests are complete.

The code below shows how this can be done:

Firstly, the image needs to be inserted within <body></body> tags and the CSS display property set to none. This will hide the image from the beginning.

<img src="processing.gif" id ="inProgress" style="display: none" />

Firstly, we use the Ajax.Responders object to register the onCreate and onComplete callbacks. The onCreate callback is triggered when an Ajax.Request object is created, and the onComplete callback is triggered when the request completes executing. The two callbacks are set to functions showProcessing and hideProcessing which in turn will show or hide the processing icon inside the document.


Ajax.Responders.register({
  onCreate: showProcessing,
  onComplete: hideProcessing
});

function showProcessing() {
  if(Ajax.activeRequestCount > 0)
    document.getElementById('inProgress').style.display = 'inline';
}

function hideProcessing () {
  if(Ajax.activeRequestCount <= 0)
    document.getElementById('inProgress').style.display = 'none'; 
}

The examples above illustrate some of the advantages of using Prototype.js for Ajax development. One of the biggest advantages is the amount of code needed to develop an application is greatly reduced and therefore ends up being more comprehensible.

Wide World of Web This was published in Wide World of Web, check every Wednesday for more stories

Related links

Comments

1

jvc - 07/02/08

Hey,

thanks for this nice article!
I only run into one problem: "if(response == 'available')" never becomes true, even if response is 'available' ?!

Joe.

» Report offensive content

2

nms - 14/03/08

can anyone help me out calling the variables into the server tables using asp.net instead of php?kindly help me out ASAP.

i need to fetch the data from ajax script to my .aspx page instead of .php file

» Report offensive content

3

Mcblaue - 13/05/08

I'm trying to pass 3 form elements using ajaxupdater but can't get it to work with anymore than 1. I've tried the below (and anything else I can find on google!) but no joy.

new Ajax.Updater('fruits', 'calculator2.php', { method: 'post', parameters: salary=$('salary')&age=$('age').serialize(true) });
return false;

» Report offensive content

4

Stone Deft - 19/06/08

Ok tnx for this I have a question about the ajax responders. One of the obstacles in ajax is to let the users know that something is loading when users click a link. What if I want the traditional way of browsers showing that something is loading like what they did here: http://www.proscubadiver.net. When you clik a link you can actually see that something is loading without refreshing the page... Will you be kind enough to give me hint on this technique and tnx

» Report offensive content

Leave a comment

You must read and type the 6 chars within 0..9 and A..F

* indicates mandatory fields.

4

Stone Deft - 19/06/08

Ok tnx for this I have a question about the ajax responders. One of the obstacles in ajax is to let ... more

3

Mcblaue - 13/05/08

I'm trying to pass 3 form elements using ajaxupdater but can't get it to work with anymore than 1. I've tried ... more

2

nms - 14/03/08

can anyone help me out calling the variables into the server tables using asp.net instead of php?kindly help me out ASAP. i ... more

Log in


Sign up | Forgot your password?

  • Staff XP stays on life support for longer

    This week's Roundup looks at Microsoft's decision to extend the life of Windows XP, the release of Microsoft Surface SDK, Firefox's new Geode plug-in, Yahoo's new tool -- Smush It and more. Read more »

    -- posted by Staff

  • Chris Duckett The good and truly awful celluloid depictions of computers

    Ever wonder why your lawyer uncle leaves the room whenever you turn over to Boston Legal? Or why your forensic science cousin can't stand crime drama? You know the answer: it’s the horrid trivialisation and dumbing down of an occupation to make it appear entertaining. Sometimes it is so unbelievable that it actually hurts and yelling at the screen is the only outlet. Read more »

    -- posted by Chris Duckett

  • Brendon Chase Apple's iPhone engineers to tour Sydney, Melbourne

    Aussie developers will be able to get up close and personal with some of the iPhone engineers in November to learn how to build applications for the platform. Read more »

    -- posted by Brendon Chase

What's on?