Feeds

Using Ajax with Prototype

More Ajax with less code

Intelligent flash storage arrays

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

Top 5 reasons to deploy VMware with Tegile

More from The Register

next story
Preview redux: Microsoft ships new Windows 10 build with 7,000 changes
Latest bleeding-edge bits borrow Action Center from Windows Phone
Google opens Inbox – email for people too thick to handle email
Print this article out and give it to someone tech-y if you get stuck
Microsoft promises Windows 10 will mean two-factor auth for all
Sneak peek at security features Redmond's baking into new OS
UNIX greybeards threaten Debian fork over systemd plan
'Veteran Unix Admins' fear desktop emphasis is betraying open source
Entity Framework goes 'code first' as Microsoft pulls visual design tool
Visual Studio database diagramming's out the window
Google+ goes TITSUP. But WHO knew? How long? Anyone ... Hello ...
Wobbly Gmail, Contacts, Calendar on the other hand ...
DEATH by PowerPoint: Microsoft warns of 0-day attack hidden in slides
Might put out patch in update, might chuck it out sooner
prev story

Whitepapers

Choosing cloud Backup services
Demystify how you can address your data protection needs in your small- to medium-sized business and select the best online backup service to meet your needs.
Forging a new future with identity relationship management
Learn about ForgeRock's next generation IRM platform and how it is designed to empower CEOS's and enterprises to engage with consumers.
Security for virtualized datacentres
Legacy security solutions are inefficient due to the architectural differences between physical and virtual environments.
Reg Reader Research: SaaS based Email and Office Productivity Tools
Read this Reg reader report which provides advice and guidance for SMBs towards the use of SaaS based email and Office productivity tools.
Storage capacity and performance optimization at Mizuno USA
Mizuno USA turn to Tegile storage technology to solve both their SAN and backup issues.