Monday, December 13, 2010

Ajax tutorial with jQuery

Introduction

AJAX is just simple technique for refreshing browser DOM with data acquired from some kind of server (Servlet/JSP, PHP, ASP.NET, ...). There is nothing specially clever in this technique.

Ajax is a less recent addition to the web toolbox than many people may realize. In 1998, Microsoft introduced the ability to perform asynchronous request as an ActiveX control (part of Outlook Web Access ).

After few years MS browser introduced standardized XMLHttpRequest (those days everything was flavored with XML :) ) object. These days you will not use XML with AJAX requests (rather JSON, or simple HTML). Google coined the term AJAX (Asynchronous JavaScript and XML -- you see!) and rest is history.

You can download example from this tutorial from my google app code SVN repository.

Plain JavaScript VS jQuery

Using plain JavaScript to implement AJAX (all cross browser JavaScript stuff) is not so easy. In a perfect world, code written for one browser would work in all commonly used browsers. But we do not live in perfect world and in this situation IE is one browser that handle AJAX in different way. The main problem is to create and instance of XMLHttpReauest object.

Let I give you some quick insight what you need to do in other to (just) get instance of this object in plain (cross browser) JavaScript:

var xhr;
if (window.ActiveXObject) {
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
else  if (window.XMLHttpRequest) {
  xhr = new XMLHttpRequest();
}
else {
  throw new Error("This browser is not ajax enabled.");
}

There are couple of things you need to consider when you handle AJAX using plain JavaScript. One is encoding, another is creating handler for response...and so on.

Now, the jQuery code for AJAX request and getting response is as follows:

$('#driverSelectionControl').load('/AjaxExampleCWP/actions/driversList.jsp');

I think we have a winner! So we will be using jQuery from now on and leveraging it great capabilities.

jQuery load() method

Perhaps the most common uses of Ajax is to grab a chunk of content from the server and stuff it into the DOM as some strategic location. jQuery do just that, it's "load" html code into wrapper set using (go figure!) load() method. It sound simple and it is simple!

Let's go straight to the example:

We have page select component with F1 race drivers names filled in. When you change driver name, his details will be pulled from server and appended to DOM without page refresh. Interesting detail in this example is that select HTML component is also populated using Ajax.

Code for initial page DOM:


Now I will show you code for Ajax stuff and explain afterwards.

$(function() {
  $('#driverSelectionControl').load('/AjaxExampleCWP/actions/driversList.jsp');

    $('#driverSelectionControl').change(function(event) {
      $('#driverDetailPanel').
        load('/AjaxExampleCWP/actions/driversDetails.jsp',
             {driverId : $(event.target).val()});
    });
});

02: Loading options html components into select component. You see how easy is to use Ajax with jQuery! :) We just need to give URL to JSP page.

Here is JSP page for driver list:






That's it. All that this JSP page do is rendering options components.

04-08(from previous example): Here we handle change event. When user select another driver (value is changed), then we load his detail from driversDetails.jsp. We pick user by passing parameter (driverId) to JSP page.

Here what JSP page look like:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


    
        
        
        
        
        
    
    
        
        
        
        
        
    
    
        
        
        
        
        
    


Driver name ${item.name}
Team name ${item.team}
Podiums ${item.podiums}
Points ${item.points}
Date of Birth ${item.birth}

You can use POST (default) or GET HTTP request method using load method. If you want to use POST (like in this example) then you send object hash as parameter to load (for example: {driverId : 205} ). If you want to initialize GET request, then you need to pass query string. If you use GET, you must ensure that your string is properly formated (names and values are URI-encoded).

If you are wondering when to use POST and when to use GET then follow this recommendations:

Use GET request when request operation that is made again and again make no change to state of server (for example when you just pulling data from server). This mean that our example is in opposite to this recommendation!
Use POST request when operation your request is initiating is non-idempotent (as opposite to idempotent like in GET). This mean, that you should use POST when you change some state on server (changing, or updating the data).

Other jQuery Ajax methods

jQuery include other methods for Ajax functionality like $.get(), $.post() for explicit GET or POST request operations.

jQuery also provides a general utility function for making Ajax requests, named $.ajax(). Under the covers, all other jQuery features uses this function. It it quite powerfull, but also complex. Feel free to investigate this function if you are interested.

No comments:

Post a Comment