This is a post about an ajax framework that was new to me. Not that it is a new framework, but I started seeing it in more and more places and they talked about it during the the springexperience as well. So I wanted to give it a go. I found out that there is a Manning Early Access Pogram book, so I bought it started reading and put some stuff in two sample applications I am creating:
Raffle application, this application demonstrates the following techniques : jpa/hibernate, springframework 2.5, and three different front end applications (wicket, gwt and spring mvc with jquery).

Training Overview, this application used almost the same architecture as the raffle application. More focus on testing with and without the springframework, and jquery together with spring mvc 2.5

So what is it all about, that jQuery. To me it is a very easy to use light weight dom browsing framework with some very handy plugins. The architecture as been made to be very extendible. Let’s start with a very easy example:

$(document).ready(function() {
	$("#easysample").hide();
});

<div id="easysample">Easy sample</div>

This sample shows a div and a piece of javascript (that should be positioned in the header within script tags). Right after the dom tree has been created and before it will be shown, the function ready will be called. Within this function we do a search on the dom for an elemen called easysample. To the result we say hide. Easy does it. This is the first time I thought about the difference between creating the dom and making it ready to be shown on the screen. The normal javascript function onLoad in the body tag waits till the whole document is shown on the screen, which is pretty strange if you know up front that you are going to change it. Next to that it looks strange as well, it is a sort of flickr in the website when starting the page. So this is what $(document).ready is about. The second part starting with function () is the callback function. We provide the ready function with what we call a callback function. The event should call this function when it occurs.

This sample is a bid stupid, because you will get a blank screen. Let’s put a link in there that will help us show the div, hide it again, and keep a counter within the div showing the amount of times it was hidden. Here is the complete code:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Easysample</title>
    <script type="text/javascript" src="js/jquery-1.2.1.min.js"></script>
    <script type="text/javascript">
        var clickTimes = 0;
        $(document).ready(function() {
            $("#easysample").hide();
            $("#togglelink").click(function() {
                $("#easysample").html("Easy sample : clicked " + ++clickTimes + " times").toggle();
            });
        });
    </script>
</head>
<body>
    <span id="togglelink">Click me</span>
    <div id="easysample">Easy Sample</div>
</body>
</html>

Again right after the document model is ready we hide the div and we assign a callback function to the click event of the span. The function html sets the provided text as the contents for the element that was found. The toggle function toggles between hide and show. You can find a running version of the sample here.

Just like hiding and showing, we an also toggle styles. Have a look at the following example code. I’ll only show the document ready part:

$("#togglelink").click(function() {
    $("#easysample").html("Easy sample : clicked " + ++clickTimes + " times").toggleClass("attention");
});

You can find a running version of the sample here

So we know how to identify an element, know how to show and hide it, can change the contents and can add style. The mentioned book covers a lot more of course, there is a lot to be said about the whole event model. This model is not very consistent across all browsers. jQuery makes it a lot easier to do. For me two other things were very important: Making things look nice without to much effort and doing some ajax. Let’s have a look at that.

For visual effects we will use a plugin that is supported by the jQuery team called UI, yes cool isn’t it? You can find more information at there website with some cool demo’s. I like the sortable table plugin. Not that I did not see more fancy scripts, and actually I am missing a filter option, but I’ll have a look at that the coming weeks. Take a look at the following code. I do not present the whole html code mode you will understand what happens. Before you can use this yourself, read about the stylesheets, the images etc. You do need to include the javascript with the table stuff in there, you need to include some styles and three images there are referenced by the style sheet.

    <link rel="stylesheet" type="text/css" href="styles/flora.tablesorter.css"/>
    <script type="text/javascript" src="js/jquery-1.2.1.min.js"></script>
    <script type="text/javascript" src="js/jquery.tablesorter.pack.js"></script>
    <script type="text/javascript" src="js/jquery.tablesorter.pager.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#datalist")
                    .tablesorter({sortList:[[2,0],[3,1]], widgets: ['zebra']})
                    .tablesorterPager({container: $("#pager")});
        });
    </script>
<table id="datalist" class="tablesorter"> ... </table>

A lot of the nice stuff is handled in the stylesheet. Please take a look at the online sample here. The above code shows the two additional scripts to load (beware, I had to download the most recent versions which can be found here). We also need to load a stylesheet, I took the one from the ui.query homepage. For the pager stuff you need to add an additional div and some icons. Download the complete package from the website and you will find the required resources. There is one thing I want to mention as well. The tablesorter function accepts a sortList parameter. This sortList is an array of arrays. Where the inner arrays contain two numbers, the first represents the column (starting at zero), the second reopresents the sorting. A zero for sorting means ascending and 1 descending. These are used as deafults when the table is creted.

We are almost at the end of my introduction. The final thing to show is some ajax to call the server. The sample will come up with a table that has some clickable fields. By clicking on the field you will obtain detailed information about the field from the server. For now the detailed information is coming from a php page and that is not working for me. But the general concept stays the same. You can find the running sample here. The most important part of the code is in the next code block.

    <script type="text/javascript">
        $(document).ready(function() {
            $("#datalist").tablesorter({sortList:[[2,0],[3,1]], widgets: ['zebra']});
        });
        function details(name) {
            $("#detailscontent").load("persondetails.php", {personname : name}, function() {
            
            });
        }
    </script>
    <body>
    ...
        <tr><td><a href="#" onclick="details('jettro')">Jettro</a></td><td>35</td><td>1.80</td><td>male</td></tr>
    ...
        <div id="detailscontent">Details</div>
    </body>

The detailscontent div is used to present the new obtained data. Within the link we call a javascrip, deatils. This javascript does load the new content for the div. This piece of code is all there is to it:

$("#detailscontent").load("persondetails.php", {personname : name}, function() {});

The function accepts the page to load (persondetails.php), the parameters to pass to the server using the request object ({personname : name}) and finally a callback function, which we do not use in the sample.
For another application I am creating (you cannot see this live, but you can see the code), I am also using this technique. In this application I am talking to a spring-mvc 2.5 application. You can find the maven generated site here (same as the one at the beginning of this blog item. You can find the complete code of this application in google code. The following piece of code should look familiar by now. It is called after clicking a link and it calls the url projectemployees.view with the parameters projectId.

        function fillEmployeesBox(projectId) {
            $("#employeesBox").load("projectemployees.view",{projectId : projectId}, function() {
                $(".zebra tr:nth-child(even)").addClass("striped");
                $("#employeesBox").show();
            });
        }

Hope you liked this short introduction into jquery. There are a lot of resources to be found on the web. Of course the jquery homepage http://jquery.com/ is a very good place to start. And I have shown a book which helps me a lot during my jquery programming.

Start using jQuery with some small samples and using spring-mvc 2.5
Tagged on: