Recently I have been rebuilding my website sellerstoolbox.com with some help from Mike Christoff who is a graphical designer in Columbus Ohio. I use tables extensively to present information about sales, inventory, and many other eCommerce related reports For this rebuild I have decided to use DataTables more extensively. It is very powerful, provides lots of great features, all while using the browser to do the work instead of the server. One of the great things about it is being able to populate the table with JSON retrieved from my server using AJAX.

The problem though is what to do once the table gets this data. I want to modify some of the cells to add color, links, and other features based on the data there. Unfortunately the normal sAjaxSource value doesn't provide a hook where I can do these things after the data is retrieved. That is where fnServerData comes into play. I learned that by proving a function to this attribute, I can do just about anything after the JSON is returned. An example looks something like the following.

 

"fnServerData": function(sSource, aoData, fnCallback) {
    $.getJSON( sSource, aoData, function (json) {
        fnCallback(json);
        oTable.fnAdjustColumnSizing();
        hideWaiting();
     } );
}

 

The code above will be called when ever JSON data is being retrieved for the table. In this case I call the fnCallback function to process the JSON data that was returned. Then I am fixing the header and table column alignment on the table, and then I am hiding the DIV that is being used as a waiting graphic while the data is being retrieved. I could just as easily called a method to update the table cells, calculate a sum or average, or any other task once the data has been loaded and put into the table.

In my case being able to hide the DIV being shown while waiting was my main reason for learning about fnServerData. But now I use it just about everywhere since I always have some cleanup or post processing I want to do to the table. This is much easier than trying to do that work and pass it back through the JSON data. I also appreciate that the work is done using the browser instead of my server so performance for my system is enhanced by having less work to do.