Feeds

Using Ajax with Prototype

More Ajax with less code

Business security measures using SSL

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. ®

New hybrid storage solutions

More from The Register

next story
New 'Cosmos' browser surfs the net by TXT alone
No data plan? No WiFi? No worries ... except sluggish download speed
'Windows 9' LEAK: Microsoft's playing catchup with Linux
Multiple desktops and live tiles in restored Start button star in new vids
iOS 8 release: WebGL now runs everywhere. Hurrah for 3D graphics!
HTML 5's pretty neat ... when your browser supports it
Mathematica hits the Web
Wolfram embraces the cloud, promies private cloud cut of its number-cruncher
Google extends app refund window to two hours
You now have 120 minutes to finish that game instead of 15
Intel: Hey, enterprises, drop everything and DO HADOOP
Big Data analytics projected to run on more servers than any other app
Mozilla shutters Labs, tells nobody it's been dead for five months
Staffer's blog reveals all as projects languish on GitHub
SUSE Linux owner Attachmate gobbled by Micro Focus for $2.3bn
Merger will lead to mainframe and COBOL powerhouse
iOS 8 Healthkit gets a bug SO Apple KILLS it. That's real healthcare!
Not fit for purpose on day of launch, says Cupertino
prev story

Whitepapers

Providing a secure and efficient Helpdesk
A single remote control platform for user support is be key to providing an efficient helpdesk. Retain full control over the way in which screen and keystroke data is transmitted.
WIN a very cool portable ZX Spectrum
Win a one-off portable Spectrum built by legendary hardware hacker Ben Heck
Storage capacity and performance optimization at Mizuno USA
Mizuno USA turn to Tegile storage technology to solve both their SAN and backup issues.
High Performance for All
While HPC is not new, it has traditionally been seen as a specialist area – is it now geared up to meet more mainstream requirements?
Security and trust: The backbone of doing business over the internet
Explores the current state of website security and the contributions Symantec is making to help organizations protect critical data and build trust with customers.