Skip to main content

Create data set navigation with the Rico LiveGrid widget

Quickly set up an Ajax-enabled alternative to traditional paging

Nikhil Parekh, Software engineer, IBM
Photo of Nikhil Parekh
Nikhil Parekh is a software engineer with the IBM Software Group at Research Triangle Park, NC, where he is involved in the design and development of tools for the mid-market industry. His main areas of interest are Java EE development, Web technologies, Web 2.0, GUI design, software engineering, software architecture, and IT security.

Summary:  With the Rico LiveGrid widget, easily add Ajax-style navigation to your Web applications in this article by software engineer Nikhil Parekh.

Date:  16 Jan 2007
Level:  Introductory
Activity:  2274 views

Traditional paging has been around ever since developers started to build dynamic Web applications. Anytime a large set of data is to be displayed, paging is used to show the user one subset of data at a time. The user navigates from one data set, or page, to another using the Next or Previous button.

Several variations of traditional paging are in use today. Some show the user First, Previous, Next, and Last buttons, some use numbers, and others employ a combination of the two. The paging concept helps both the user and the server efficiently deal with large sets of data.

The recent popularity of Ajax has changed the way developers design and build Web applications, however. Ajax gives you the ability to build Web applications that look and behave more like traditional desktop applications. Several open-source and commercial JavaScript/Ajax frameworks and libraries make the Ajax model even easier to implement by providing ready-to-use widgets. Developers can use these widgets to add rich features and functionality to Web applications without a lot of effort.

Download Rico

To follow the examples in this article, you will need to download the Rico library. You can download rico.js and prototype.js from the Rico homepage. Note that the Rico library uses features from an open-source framework called Prototype, thus prototype.js is required.

One such framework is Rico. In this article, I will briefly introduce you to this open-source, client-side JavaScript framework, and then focus on one of its widgets, LiveGrid. As I will demonstrate, you can implement LiveGrid to replace the traditional paging model in your Web applications.

The Rico library

The Rico library is a JavaScript file that you can include in any Web page to give that page access to a rich set of features and widgets. The library handles many complex implementation details, including cross-browser compatibility, leaving you free to focus on creating page functionality.

To take advantage of a Rico feature or widget is very simple: you only write a few lines of code to integrate that feature or widget on a given page. For example, Rico provides a very simple interface to add Ajax support to your Web pages. It takes just five or six lines of JavaScript code to add Ajax functionality to a Web page, after which you can make Ajax requests to the server and deal with responses from the server. All of this is possible without having to directly deal with the XmlHttpRequest JavaScript object.

Visual effects such as drag-and-drop are also very easy to add to your Web pages using Rico. With the Rico library you can define any HTML or JavaScript object as draggable, or as a drop zone. Once you've done this, draggable objects can be dragged around on the page and can be dropped in one or more user-defined drop zones. Rico handles all the implementation details for this functionality, so you only have to write a few lines of code.

To add cinematic effects such as fading, animated resizing and positioning, and rounding shapes is also fairly simple with Rico. One of the most popular Rico widgets is the Accordion, which presents a collection of collapsible drawers. Each drawer has a drawer heading and a content area. Clicking on a drawer heading shows the content for that drawer and hides the content in other drawers. Another very popular widget is the LiveGrid, which I will focus on for the remainder of the article.


A simple LiveGrid

The LiveGrid in Figure 1 is a scrollable table of information where the data in the table is updated on-the-fly each time the user clicks on the scrollbar. The table is connected to a live data source and updates to the table are made with the help of Ajax.


Figure 1. LiveGrid in initial state
LiveGrid in initial stat

The LiveGrid shows a scrollable list of 20 movies. Each time the user clicks on the scrollbar, the contents of the table are updated with a new set of movies. Rico makes Ajax calls to the server as and when it needs a new set of data. It uses buffering for better performance and also to make the scrolling smooth. Thus each click on the scrollbar might not result in an Ajax request. Rico will first use data from its buffer to update the grid and it will make an Ajax request for more data when it has used up all the data from its buffer. Figure 2 shows what the LiveGrid would look like after the user had clicked on the scrollbar once. The LiveGrid also supports column sorting. If sorting is implemented in the grid, the user can click on column name and sort the column.


Figure 2. LiveGrid after a click on the scrollbar
LiveGrid in initial stat

Creating a LiveGrid

For a learning example I will show you how to create the Movies LiveGrid above. If you haven't already done so you will need to download rico.js and prototype.js from the Rico homepage. Note that the Rico library uses features from another open-source framework called Prototype, thus prototype.js is required. You will also need a Web/application server to handle the Ajax calls from Rico. For this example I will use Apache Tomcat 6.0.

You can begin by coding the client side of the example. Start out with a clean page. The first thing you need to do is include the rico.js and prototype.js libraries in the page. Assuming that the library files are in the same directory as the HTML file, Listing 1 shows how you would include the libraries in the page.


Listing 1. Start with the Rico and Prototype libraries

<script src="prototype.js"></script>
<script src="rico.js"></script>

Next, you add a placeholder for the label that displays the text "Showing 1 - 5 of 20 Movies" in Figure 1. This label is updated each time the user clicks on the scrollbar.


Listing 2. Setting the showLabel

<div id="showingLabel" >Showing 1 - 5 of 20 Movies</div>

Then, you add the LiveGrid header that shows the names of the columns (such as Number, Title, Year) in Figure 1.


Listing 3. Adding the LiveGrid header

<table cellspacing="0" cellpadding="0" width="400">
    <tr>
        <th bgcolor="#999999" width="30">#</th>
        <th bgcolor="#999999" width="310">Title</th>
        <th bgcolor="#999999" width="60">Year</th>
    </tr>
</table>

Finally, you're ready to create the table that Rico will use to show the movie data. The table that you create with the code below has six rows and three columns. Every alternate row in the table has a light-grey background. For the LiveGrid to work correctly, you always want to create an extra row in the table. So, if you want to create a LiveGrid to show five rows, the HTML table that you create will need to have six rows. Without the extra row LiveGrid's scrolling function will misbehave. Listing 4 shows the code needed to create the HTML table that the LiveGrid will use.


Listing 4. LiveGrid data HTML table

<div id="movieDiv" style="float:left">
    <table id="movie_grid" cellspacing="0" cellpadding="0" 
        width = "400px" style="border:1px solid #ababab" >
            <tr>
        		<td width="30"> </td>
                <td width="310"> </td>
                <td width="60"> </td>
            </tr>
            <tr>
                <td bgcolor="#eeeeee" width="30"> </td>
                <td bgcolor="#eeeeee"  width="310"> </td>
                <td bgcolor="#eeeeee"  width="60"> </td>
            </tr>
            <tr>
                <td width="30"> </td>
                <td  width="310"> </td>
                <td  width="60"> </td>
            </tr>
            <tr>
                <td bgcolor="#eeeeee" width="30"> </td>
                <td bgcolor="#eeeeee"  width="310"> </td>
            <td bgcolor="#eeeeee"  width="60"> </td>
            </tr>
            <tr>
                <td width="30"> </td>
                <td  width="310"> </td>
                <td  width="60"> </td>
            </tr>
            <tr>
                <td bgcolor="#eeeeee" width="30"> </td>
                <td bgcolor="#eeeeee"  width="310"> </td>
                <td bgcolor="#eeeeee"  width="60"> </td>
            </tr>
    </table>
</div>


Defining the LiveGrid

With the table and data set up, you're ready to define a JavaScript function that will turn the HTML table in Listing 4 into a Rico LiveGrid. The function shown in Listing 5 is called the loadGrid function.


Listing 5. Defining the Rico LiveGrid

<script>
    function loadGrid() {
        var opts = {   prefetchBuffer: true, onscroll : updateLabel };
        var liveGrid = new Rico.LiveGrid( 'movie_grid',5, 20, 'MovieData', opts); 
    }
</script>

The first line in the loadGrid function specifies the options for the LiveGrid. When you set the prefetchBuffer option to true, you tell Rico to fetch data while it constructs the LiveGrid. If you set this option to false the LiveGrid will not have any data when it loads. It will only show data once you click on the scrollbar.

Using the onScroll option you can define a function that you want Rico to call each time the user clicks on the scrollbar. In this case you want to update the label that says "Showing 1 - 5 of 20 Movies". To do this you will define a JavaScript function called updateLabel and have Rico call it each time the user clicks on the scrollbar. You can use the onscrollidle option, which you haven't used in this example, to call JavaScript functions when scrolling pauses or stops.

Another useful option is requestParameters, which you can use to send extra parameters to the service that will handle Ajax requests. You can also use requestParameters to filter data that is shown in the LiveGrid. For example, if you only wanted to show action movies in the LiveGrid, you can set requestParameters to genre=action and the service handling the Ajax calls would return movies matching that genre.

The second line in the loadGrid function actually declares the LiveGrid. The first parameter in the constructor is the ID of the HTML table that will be converted into a LiveGrid. In this case the ID was "movie_grid". The second parameter indicates how many rows you want to show in the LiveGrid, in this case five rows. The third parameter indicates the maximum number of rows you will have in the LiveGrid, in this case 20. The fourth parameter should be the URL of the server-side script/servlet that will handle the Ajax calls. For this example I created a servlet called MovieData that handles the Ajax requests from Rico. I will discuss this at greater length later in the article. The last parameter is the variable that you declared in line 1 of the function that defines the options for your LiveGrid, in Listing 5.

Loading and updating the grid

You need to call the loadGrid function whenever the HTML page is loaded. Listing 6 shows how this is accomplished.


Listing 6. Calling the loadGrid

<body onload="javascript:loadGrid()">

Finally, you define the function that will update the label above the Movie LiveGrid, as shown in Listing 7.


Listing 7. updateLabel function

<script>
    function updateLabel( liveGrid, offset ) {
        $('showingLabel').innerHTML = "Showing " + (offset+1) + " - " + 
        (offset+liveGrid.metaData.getPageSize()) + " of " + 
        liveGrid.metaData.getTotalRows() + " movies";
	}
</script>

The updateLabel function is called each time the user clicks on the scrollbar. It basically uses variables form the Rico library to construct a string like "Showing 1 - 5 of 20 movies". If you are not familiar with the Prototype JavaScript framework, you can use the $(DIVNAME) syntax to refer to any object on the page with an ID that matches DIVNAME. Thus $('showingLabel').innerHTML is equivalent to document.getElementById("showingLabel").innerHTML. In this case, you replace the innerHTML value of the DIV tag with an updated string each time the user clicks on the scrollbar.


Setting up the server side

Much of the coding in Rico happens on the client side, but you have a few important things to do on the server side. Namely, you need to set up the server-side script or servlet to handle the Ajax calls. As I mentioned earlier, I created an example servlet to handle the Ajax requests from Rico. Listing 8 shows how the XML response from the servlet must look in order to work correctly with the LiveGrid widget. The XML response must be in the following format for the LiveGrid to work.


Listing 8. The required format of the XML response

<?xml version="1.0" encoding="ISO-8859-1"?>
    <ajax-response>
       <response type="object" id='movie_grid_updater'>
            <rows update_ui='true' >
               <tr>
                   <td>1</td>
                   <td>Star Wars</td>
                   <td>1977</td>
               </tr>
               <tr>
                   <td>2</td>
                   <td >The Godfather</td>
                   <td>1972</td>
               </tr>
               ...
            </rows>	
    </response>
</ajax-response>

Notice that the first two words ("movie_grid") of the id attribute in the response tag match the id attribute in the HTML table previously defined for the LiveGrid. These need to match for Rico to update the data in the LiveGrid. In a normal situation the server-side script or servlet connects to a data source and generates XML in the above format. Rico handles the process of extracting data from this XML response and populating the LiveGrid with the new data. It is important to set the content-type of the response to "text/xml". The LiveGrid will not work if you fail to do this. The XML version and encoding also must be set to "1.0" and "ISO-8859-1", respectively. You can set the content-type in Java™ code as shown in Listing 9.


Listing 9. Setting the content-type of the Ajax response

response.setHeader("Content-Type", "text/xml");

Four data parameters

Now you might wonder how the script or servlet knows when to generate which sets of data. Earlier in the article, I mentioned that the Rico framework uses buffering and will request data as and when it needs it. When Rico makes an Ajax request to the backend it might send up to four parameters as a query string in the URL. When available, all of these parameters must be used by the backend in order to generate the correct Ajax response. The four parameters are:

offset
Indicates what the first row of data should be in the set of data to be returned. For the sake of example, say that LiveGrid was initially loaded with an offset of zero. Rico fetched 150 rows of data during the initial load and used buffering to store the data. After displaying all 150 rows it makes an Ajax request to the backend for new data with the value of offset set to 151.
page_size
Indicates the number of rows of data that Rico wants the backend to return.
sort_col
The column on which to sort the data before it is sent to Rico.
sort_dir
Indicates whether to sort the column in ascending or descending order (ACS or DECS).

Once you write all of the above code, you should be able to point your browser to the HTML page and see the LiveGrid in action.


In conclusion

Rico is an open-source JavaScript library that you can use with Web applications to provide users with a rich set of features. In this article I explained the basics of Rico and introduced you to the LiveGrid widget, using a working example to show you how it can replace traditional paging in your Web applications.


Resources

Learn

Get products and technologies

Discuss

About the author

Photo of Nikhil Parekh

Nikhil Parekh is a software engineer with the IBM Software Group at Research Triangle Park, NC, where he is involved in the design and development of tools for the mid-market industry. His main areas of interest are Java EE development, Web technologies, Web 2.0, GUI design, software engineering, software architecture, and IT security.

Comments (Undergoing maintenance)



Trademarks  |  My developerWorks terms and conditions

Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development, Open source
ArticleID=187844
ArticleTitle=Create data set navigation with the Rico LiveGrid widget
publish-date=01162007
author1-email=nparekh@us.ibm.com
author1-email-cc=htc@us.ibm.com

My developerWorks community

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Rate a product. Write a review.

Special offers