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.

Tagged on:     

9 thoughts on “Start using jQuery with some small samples and using spring-mvc 2.5

  • April 19, 2012 at 3:27 pm
    Permalink

    Hi,

    Can you please give me the source code for both php and Spring MVc versions, I appreciate your help.
    Thanks lot

    Reply
  • December 21, 2009 at 8:51 am
    Permalink

    To bad you do not use a real name (I think) but a short response is what I can give. Before you start moaning about stuff you get for free check that you are reading a blog post of almost two years old. Things have changed so maybe some things don’t work like they should. Of course you can ask a question and maybe people will help you. As for the maven part, I don’t mind that you keep using ant to build, I prefer the standardized way of maven. If that is not what you want, you might try to goolge another blog post that better suits your needs.

    Reply
  • December 18, 2009 at 1:49 am
    Permalink

    The Web (Spring MVC project) didn’t work worth a darn – gets a JPA connection error exception. I’m running other Spring MVC apps on my Tomcat 6, so don’t go there. Also – why do you guys complicate your project development lives with Maven?

    Reply
  • September 16, 2009 at 1:22 pm
    Permalink

    Hi,

    I am new to this jquery.I am expecting two answeers from you.Is there to insert any maven plugin to use jquery.
    And second thing is, I want to create a dropdown list having values from 1 to 10 using jquery.

    Reply
  • January 12, 2009 at 12:06 pm
    Permalink

    Hi,
    I have checked out your training overview application from your repo, it is great work. I have used jquery before, but we had problems with Weblogic 10.3. We used jquery validate plugin in some apps and it doesn’t run on Weblogic 10.3, although the same apps work on jboss, tomcat. Have you come across such issues.
    Also, do you have some pdf, html docs and a sample schema/sql file for your training overview application.

    –Irshad Buchh
    Senior Principal Consultant.

    Reply
  • December 29, 2008 at 10:30 am
    Permalink

    BTW for building in eclipse just execute “mvn eclipse:eclipse” or “mvn eclipse:m2eclipse” depending on what maven approach you use for eclipse. I recommend the m2eclipse plugin (make sure to get version 0.0.12 or later to deal properly with parent poms) and the latter command.

    While it works for maven on the command line, your duplicate groupId line is unneeded and I’ve seen it cause problems in projects before. So you have <groupId>nl.gridshore.samples.raffle</groupId> in the parent section, but remove the second instance of it below in all the child pom.xml files. Also you can just use project.version instead of project.parent.version, but they are equivalent in this case.

    Just finished Jquery in Action and I highly recommend it. After 10 years of hating Javascript, I might have to re-examine my stance. Jquery is straightforward and dare I say elegant.

    There a good blog post I saw on Spring MVC and JQuery:

    http://www.infoq.com/articles/First-Cup-Web-2.0-Joel-Confino

    Paul Sundling
    http://www.gamerleague.com

    Reply
  • December 29, 2008 at 6:26 am
    Permalink

    You’re doing a good job of breaking the projects into different projects, but you’re not following the maven best practice of using dependencyManagement. Essentially in the parent pom, you should include all the dependencies for all the projects with versions in a dependencyManagement section and then include the dependencies WITHOUT versions in the actual projects. As the number of modules/projects scales up your chances of multiple projects with the same dependencies rises. This keeps the projects all using the same version. This is compatible with your properties approach now. Just use properties where there are multiple dependencies with the same value, like with spring. Other items don’t need to use properties, just dependencyManagement.

    parent pom

    <properties>
    <spring.version>2.5.6</spring.version>
    </properties>

    <dependencyManagement>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>${spring.version}</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>${spring.version}</version>
    </dependency>
    </dependencyManagement>

    child pom

    <dependencies>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    </dependency>
    </dependencies>

    Paul Sundling
    http://www.gamerleague.com

    Reply
    • December 29, 2008 at 9:39 am
      Permalink

      Thanks for your extensive comment. I really appreciate that. Though I do not completely agree on the usage, a lot of my colleagues are using it as well. We try to add some strange things we have to a super pom. To do it in general for all my dependencies is to much in my opinion. I do not like to have the dependencies at multiple places. I hardly ever have a project that needs two modules with hibernate for instance.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>