Monday, August 3, 2009

AJAX using jQuery

Hello!

Here's a short description on implementing AJAX using jQuery.

AJAX stands for Asynchronous JavaScript and XML. Generally, whenever some data is requested from the server, an http request is sent to the server, where it is processed and a response is sent back to the browser which is displayed to the user. Thus, if there are many different divisions in the browser containing some information (like some text fields containing data filled by the user, etc.), and if a submit button for one of the forms is clicked, the data in all the other divisions is lost. Also, the entire page needs to be refreshed. With AJAX, an XMLHttpRequest object is sent to the browser instead of a normal request. This sending of request is achieved through the use of JavaScript and it happens asynchronously wrt rest of the page. Hence, the name Asynchronous Javascript and XML.

In order to send an http request, we need to send the following 3 parameters:

1. method:

This can take values GET, POST, DELETE, HEAD and PUT. GET and POST are generally used and can meet all requirements.
The details of GET and POST method can be found here:
http://www.cs.tut.fi/~jkorpela/forms/methods.html
http://www.webdevelopersnotes.com/basics/http_client_methods_get_post.php3

2. action:

This is the url of the server side script which would process the request.

3. asynchronous:

when set to true, indicates that it is an asynchronous request.

In addition to this, we also need to send the parameters in key value pairs.

A useful tutorial for learning ajax is available at http://www.w3schools.com/Ajax/default.asp

A small example on AJAX using jQuery:

To start off, what is jQuery?

jQuery is a JavaScript Library that eases event handling, animating and AJAX interactions. It is a frame work that provides the developer with a set of functions, through which implementation of JavaScript related code would be simplified.

Unzip this file. The folder css contains a css file, which does some trivial styling. The img folder contains a .gif file which acts as a 'loading' symbol. What now remains are two important files, index.html and two.jsp.

index.html

This is a simple html page. In the body tag, there's a form created which is used to accept the details from the user (Will come back to method and action attributes used in form tag, later). Each of the fields use an id as these elements are accessed through their id's. Nothing worth noticing in this part. Lets move on to the head tag. The script tag defines a javascript file whose source is located on the google servers. This file contains everything related to the framework. It can also be downloaded at http://jquery.com/ However, using the prior method has the advantages of the file being kept updated with the improvements in the framework.

This is followed by another script, which contains the ajax call. $(); is a function which stands for $(document).ready() (and is an alternative to jQuery();) i.e. it is called when the page has loaded. It returns a jquery object.

An anonymous function is created here "$(function() {" to perform the appropriate task. All the functions that are to be executed when a particular event occurs are written inside this anonymous function. If there's some function to be performed at the load of the page, its written inside this anonymous function and outside all of the inner functions. In this case, I have defined and initiated a variable i (Its not used anywhere, just there for example sake).

"$('#submit').click(function() {" is called when the HTML element with id submit is clicked and when that happens, another anonymous function is called which is defined right there, to do the appropriate task. $('#container') returns the HTML element with id container, and append function is used to append HTML code to this division. In this case, an image is being loaded. $('#name').val(); returns the value stored in the textbox with id name.



$.ajax({
url: 'two.jsp',
type: 'POST',
data: 'name=' + name + '&email=' + email + '&comments=' + comments,

success: function(result) {
$('#response').remove();
$('#comments').hide().fadeIn(1500);
$('#container').append('<p id="response">' + result + '</p>');
$('#loading').fadeOut(500, function() {
$(this).remove();

});

}
});



This is an ajax block used to send ajax requests. The url, which in general would be a controller, is specified along with the method used which is POST in this case. The data is sent in key value pairs separated by '&'. Whether you use GET or POST, as the entire page is not refreshed, the url does not change.

"success: function(result)" indicates, after the request is handled, this function should be called, with the response text in the result variable. And the appropriate activities to be performed, that is response handling is done here.

"$('#response').remove();" is written so that the response is not displayed multiple times when the Go! button is pressed.

"$('#comments').hide().fadeIn(1500);" is just an effect created.

"$('#container').append('

' + result + '

');
"appends the result to the end of the container tag.

$('#loading').fadeOut(500, function() {
$(this).remove();
});


This is used to give a fadeOut effect to the image, and the operation fadeOut takes place for a duration of 500 ms and after this time, the image is removed.

The request is handled by two.jsp (Generally you use a servlet here). It uses" request.getParameter("name")" to retrieve the value name and prints the same appended to hello in the response. Note that ("name") corresponds to the "name" in the url in the ajax request and not the name "name" in the HTML page, although both are same here. This response is handled by the function as described above.

Finally, all this requires javascript to be enabled on your browser. What if that's not the case! We need to build a robust application taking care of all possibilities. In that case



<form method="post" action="two.jsp">

comes into picture wherein a normal http request is sent and the result is displayed on another page. Try the same application with javascript disabled in your browser.

That's about a sample code on AJAX using jQuery. Hope you enjoyed reading this. Any suggestions and questions are welcome. Just use the post new comment below this blog.


P.S.: Can anyone please help me with attaching files here or some other server?

1 comment:

  1. hey its good it would be better if you could elaborte it more in ur next blog anyways this was also nice :)

    ReplyDelete