Feeds

Using Ajax with Prototype

More Ajax with less code

The Power of One Brief: Top reasons to choose HP BladeSystem

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

Securing Web Applications Made Simple and Scalable

More from The Register

next story
Apple fanbois SCREAM as update BRICKS their Macbook Airs
Ragegasm spills over as firmware upgrade kills machines
HIDDEN packet sniffer spy tech in MILLIONS of iPhones, iPads – expert
Don't panic though – Apple's backdoor is not wide open to all, guru tells us
NO MORE ALL CAPS and other pleasures of Visual Studio 14
Unpicking a packed preview that breaks down ASP.NET
Captain Kirk sets phaser to SLAUGHTER after trying new Facebook app
William Shatner less-than-impressed by Zuck's celebrity-only app
Do YOU work at Microsoft? Um. Are you SURE about that?
Nokia and marketing types first to get the bullet, says report
Microsoft takes on Chromebook with low-cost Windows laptops
Redmond's chief salesman: We're taking 'hard' decisions
Cheer up, Nokia fans. It can start making mobes again in 18 months
The real winner of the Nokia sale is *drumroll* ... Nokia
EU dons gloves, pokes Google's deals with Android mobe makers
El Reg cops a squint at investigatory letters
prev story

Whitepapers

Designing a Defense for Mobile Applications
Learn about the various considerations for defending mobile applications - from the application architecture itself to the myriad testing technologies.
How modern custom applications can spur business growth
Learn how to create, deploy and manage custom applications without consuming or expanding the need for scarce, expensive IT resources.
Reducing security risks from open source software
Follow a few strategies and your organization can gain the full benefits of open source and the cloud without compromising the security of your applications.
Boost IT visibility and business value
How building a great service catalog relieves pressure points and demonstrates the value of IT service management.
Consolidation: the foundation for IT and business transformation
In this whitepaper learn how effective consolidation of IT and business resources can enable multiple, meaningful business benefits.