Archive

Posts Tagged ‘Prototype’

Basic AJAX using Prototype

July 12, 2010 Leave a comment

We start by creating a basic maven project with Struts. The idea is to accept text in a html text box, make a round trip to the server , capitalize the text (upper case it) and send it back as the response to the client. Our action class UpperCaseAction will have the following code in the execute method. The UpperCaseForm will have just one String attribute , text.

UpperCaseForm upperCaseForm = (UpperCaseForm)form;
upperCaseForm.getText().toUpperCase();
PrintWriter pw = response.getWriter();
pw.write(upperCaseForm.getText().toUpperCase());
pw.close();


We will create a jsp with a simple text box and a button. The onclick event on the button will fire a function in javascript that will make the Ajax call. The following is code uses prototype.js that makes that call

new Ajax.Request('../upperCaseSubmit.do', {
 method : 'get',
 parameters: $('textForm').serialize(true),
 onSuccess: function(response) {
 $('result').innerHTML = response.responseText;
 },
 onFailure: function(){
 alert('Error in processing request ...');
 }
 });


The code is self explainatory. It makes a call to the action upperCaseSubmit using ‘GET’. We have one parameter that will be sent in the request, the text field. If the call is a success the function defined by onSuccess is executed and we replace the innerHTML of a div with the upperCase of the text we received back.
If the call fails, an alert message is displayed. The serialize method formats the form data into a string.

Prototype has some listener functionality that we can utilize to know when a AJAX call has been placed.
Using the following code, we can turn on an image if at least one AJAX call is pending.

Ajax.Responders.register({
 onCreate: function() {$('loading').show();} ,
 onComplete: function() {
 if(0 == Ajax.activeRequestCount)
 $('loading').hide();
 }
 });


We can easily create a loading gif that we can use in the image tag from here. http://ajaxload.info/

Advertisements