Feeds

Using Ajax with Prototype

More Ajax with less code

High performance access to file storage

Tutorial: In the Introduction to Developing Web Applications with Ajax article we discussed the procedure used to create an Ajax application. As a developer, you probably noticed that the client JSP included a lot of JavaScript. Prototype is a JavaScript library for developing dynamic web applications, which aims to replace much of the JavaScript code in Ajax applications with its own Prototype functions. In this article, we’ll develop the same application, but using the Prototype library.

Using Prototype, the $() utility function replaces the document.getElementById() function. For example, a form div element, ‘formDiv’, is retrieved with prototype as follows:

var formDiv = $('formDiv'); 

The $F() function is used to retrieve the value of a form element. For example:

var field1=$F('field1'); 

The $A() function is used to create an Array object from a node list or an enumerable list. For example, an Array object may be created from a NodeList object and the Array object navigated to retrieve node values.

The Prototype library provides the Ajax.Request class to send an HTTP request using the XMLHttpRequest object. The Ajax.Updater class is a sub class of the Ajax.Request class and is used to update a specified form element with a XMLHttpRequest response. The Ajax.PeriodicalUpdater class is similar to Ajax.Request class and is used to update a form element periodically. For a complete listing of Prototype functions and classes refer to the Protoype documentation.

Installing Prototype

As we’re using the same application as in this article, you should install the software and create an Eclipse project as explained there.

Now download the Prototype library and extract the tar file to a directory. Copy prototype.js from <prototype-1.4.0>/dist directory to the Prototype project in Eclipse. The prototype.js file should be in the same directory as the inputForm.jsp file as shown in Figure 1.

Shows Prototype Application Directory Structure.

We also need to modify the build.xml file to include prototype.js in the WAR file generated. The modified build.xml is available in the Resources zip file.

Configuring Prototype in an Ajax Application

We’ll add Prototype library functions and classes to the Ajax application’s inputForm.jsp. To access the prototype.js library, add the following <script/> element to inputForm.jsp\\\;

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

In the Ajax application version without the prototype library, the catalogId field is retrieved with get getElementById() function and the value is retrieved with value attribute as shown below.

var catalogId = document.getElementById("catalogId").value;

To reduce the amount of JavaScript code, retrieve the catalogId value with Prototype function $F().

var catalogId = $F('catalogId'); 

In the non-Prototype version, the form elements are retrieved with the getElementById() function. For example, the validationMessage div is retrieved as follows:

var validationMessage
    = document.getElementById("validationMessage");

We replace the getElementById() function with the Prototype function $():

var validationMessage = $('validationMessage'); 

In the non-Pprototype version, an XMLHttpRequest object is created with the XMLHttpRequest constructor or the ActiveXObject constructor. The callback method is registered with the XMLHttpRequest object and the HTTP request sent to the server. The callback method is invoked when the request state changes and when the request is complete, the HTTP response is processed.

The Prototype library provides Ajax.Request class to send an XMLHttpRequest request. First you need to define a variable for servlet url and a variable for url parameters:

var catalogId = $F('catalogId');
var url = 'validateForm';
var pars = 'catalogId=' + catalogId;

Then you create a Ajax.Request object with the servlet url. The options value is specified with JSON (JavaScript Object Notation). Set the options property method to 'get'. Specify the parameters options property and set the asynchronous property to true. Specify the callback method with the onComplete property. The XMLHttpRequest gets created and sent to the specified url. When the request is complete, the showResponse function is invoked. The function registered with the onComplete property is invoked with an argument containing the XMLHttpRequest object and an argument containing the HTTP response header.

var ajaxRequest = new Ajax.Request(url, {
    method:       'get', 
    parameters:   pars, 
    asynchronous: true,
    onComplete:   showResponse
});

function showResponse(xmlHttpRequest, responseHeader) {
    // Process HTTP response and update input form
}

The showResponse function retrieves the XML response from the server and updates the input form:

var xmlMessage = xmlHttpRequest.responseXML;

The inputForm.jsp with JavaScript code replaced with Prototype library functions and Ajax.Request class is available in the resources zip file. Build and deploy the Ajax application similar to the procedure discussed in the previous Ajax article.

So, in the end, the Ajax functionality of the Prototype application is the same as the non-Prototype application; but there’s less JavaScript code. This probably goes a long way towards explaining the survey by Ajaxian.com, which found that Prototype was the most commonly used Ajax framework. ®

High performance access to file storage

More from The Register

next story
Windows 8.1, which you probably haven't upgraded to yet, ALREADY OBSOLETE
Pre-Update versions of new Windows version will no longer support patches
Android engineer: We DIDN'T copy Apple OR follow Samsung's orders
Veep testifies for Samsung during Apple patent trial
OpenSSL Heartbleed: Bloody nose for open-source bleeding hearts
Bloke behind the cockup says not enough people are helping crucial crypto project
Microsoft lobs pre-release Windows Phone 8.1 at devs who dare
App makers can load it before anyone else, but if they do they're stuck with it
Half of Twitter's 'active users' are SILENT STALKERS
Nearly 50% have NEVER tweeted a word
Windows XP still has 27 per cent market share on its deathbed
Windows 7 making some gains on XP Death Day
Internet-of-stuff startup dumps NoSQL for ... SQL?
NoSQL taste great at first but lacks proper nutrients, says startup cloud whiz
US taxman blows Win XP deadline, must now spend millions on custom support
Gov't IT likened to 'a Model T with a lot of things on top of it'
Microsoft TIER SMEAR changes app prices whether devs ask or not
Some go up, some go down, Redmond goes silent
prev story

Whitepapers

Securing web applications made simple and scalable
In this whitepaper learn how automated security testing can provide a simple and scalable way to protect your web applications.
Five 3D headsets to be won!
We were so impressed by the Durovis Dive headset we’ve asked the company to give some away to Reg readers.
HP ArcSight ESM solution helps Finansbank
Based on their experience using HP ArcSight Enterprise Security Manager for IT security operations, Finansbank moved to HP ArcSight ESM for fraud management.
The benefits of software based PBX
Why you should break free from your proprietary PBX and how to leverage your existing server hardware.
Mobile application security study
Download this report to see the alarming realities regarding the sheer number of applications vulnerable to attack, as well as the most common and easily addressable vulnerability errors.