Developer

Simpler Ajax development with Prototype.js

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.

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 

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 

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.

Editor's Picks

Free Newsletters, In your Inbox