Home / How-To & Tutorials / DataTables Live Ajax Plugin – Keep your AJAX sourced tables up to date

DataTables Live Ajax Plugin – Keep your AJAX sourced tables up to date

I’m a big fan of the Open Source jQuery plugin DataTables. Out of all the jQuery plugins I have used, I feel comfortable saying it’s one of the most stable and powerful.  For those of you who don’t know what DataTables is…

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, and will add advanced interaction controls to any HTML table.

 

Pretty basic, but very powerful and easy to use. It also comes with an extremely diverse and powerful API, that let’s you control almost every aspect of the table, as well as write your own plugins, which is what I have been getting into lately.

DataTables allows you to pull the source of the tables from the DOM, from a JSON data structure, or an AJAX Source. This plugin takes advantage of the AJAX sourced data tables.

I hang out in the DataTables forums every so often, and I saw a couple requests from people who wanted a way to update just the rows that need updating in the table, and while there is a useful API method, ajax.reload(), that method will reload the entire table, which may be a little overboard if you have thousands of rows and only a single row needs to be added/updated/removed.

I went ahead and created a new plugin to handle this, DataTables Live Ajax.

To use it, just checkout the git repository, include the JS file called dataTables.liveAjax.js, then when you initialize your DataTables instance, configure the setting called liveAjax.

GIT RepoLive Demos

How It Works

The concept is pretty basic really. Every n milliseconds (default is 5000, which is 5 seconds), there will be a new AJAX request to the data source that was configured in the DataTables instance. The new data will be compared to the current data, and the changes will be made accordingly.

Ideally, it would be better to use WebSockets, as opposed to iterating over AJAX calls, which is much more “expensive” in terms of resources, but that may not always be optional. I went with the AJAX calls initially because it was quicker than having to setup a WebSocket server, but without a doubt, the WebSockets would be the way to go, and I will be switching over to a WebSocket server in the next revamp (soon!).

One thing you need to realize though, is that the plugin needs to have a way to compare each row to it’s exact counterpart within the new JSON data. If the AJAX source contains arrays for the row data, then that isn’t possible. So what is recommended, is to use objects for the row data, and set the unique row identifier via the rowId setting, or you can use the default one, which is DT_RowId.  If you don’t set a row ID for your data, then theres no way for the plugin to know what rows need updating, thus the entire table is reloaded if any discrepancies are found in the new data source.. Which is basically the same thing as the ajax.reload() API method.

If you are already familiar with DataTables, and using an AJAX source for your table, then you probably know what I’m talking about.

Examples

Basic Example – This will check for any changes in 5 second intervals, and update the data accordingly.

$('#example').DataTable({
    ajax: 'dataSrc.php',
    rowId: 'emp_id',
    liveAjax: true
});

Advanced Example – This ones a bit more complicated. Just to show you how you can take advantage of some of the existing options for the plugin.

$('#example').DataTable({
    ajax: {
        url: 'dataSrc.php',
        type: 'POST',
        data: { dataSrc: 'something'},
        dataSrc: 'something'
    },
    rowId: 'emp_id',
    liveAjax: {
        // Update every 4.5 seconds
        interval: 4500,
        // Enable DT XHR Callbacks for all AJAX requests
        dtCallbacks: true,
        // Abort the XHR Polling if one of these errors were encountered
        abortOn: ['error', 'timeout', 'parsererror', 'abort']
    }
});

Initialization Options

While I was making this, I added an option for almost everything I could think of. This plugin was just created, so while I am sure I may be making some updates, I will try to keep the options the same throughout all the versions, but heres a list of the existing options:

Parameter Type Default Description
liveAjax boolean true Enable/Disable liveAjax plugin
liveAjax.interval number 5000 Interval to check for updates (in milliseconds)
liveAjax.dtCallbacks boolean false This will determine if the DataTables xhr callbacks should be executed for every AJAX Request
liveAjax.abortOn array error, timeout, parsererror Cease all future AJAX calls if one of these statuses were encountered
liveAjax.noUpdate function N/A Callback executed when no discrepancies were found in the new JSON data; (Parameters: [object] DataTables Settings, [object] JSON Data for table; [object] XHR Object)
liveAjax.onUpdate function N/A Callback executed when discrepancies were found in the new JSON data, and the table was updated; (Parameters: [object] DataTables Settings, [object] Updated/Deleted/Created row data, [object] New JSON Data for table; [object] XHR Object)

LiveAjax Events

The LiveAjax plugin fires off it’s own events. Just as all the DataTables events are named eventName.dt, the LiveAjax events are named eventName.liveAjax. Heres the current list of events:

Event Description Parameters
init.liveAjax Triggered when liveAjax was initiated on a new table [object] Event, [object] DataTables Settings, [object] XHR Object
xhrErr.liveAjax Triggered for all XHR Errors [object] Event, [object] DataTables Settings, [object] XHR Object, [string] Error Thrown
xhrErrTimeout.liveAjax Triggered when an XHR timeout was encountered [object] Event, [object] DataTables Settings, [object] XHR Object, [string] Error Thrown
xhrErrError.liveAjax Triggered when an XHR error was encountered [object] Event, [object] DataTables Settings, [object] XHR Object, [string] Error Thrown
xhrErrParseerror.liveAjax Triggered when an XHR parsererror was encountered [object] Event, [object] DataTables Settings, [object] XHR Object, [string] Error Thrown
xhrErrAbort.liveAjax Triggered when an xhr abort was encountered [object] Event, [object] DataTables Settings, [object] XHR Object, [string] Error Thrown
xhrErrUnknown.liveAjax Triggered when an unknown XHR error was encountered [object] Event, [object] DataTables Settings, [object] XHR Object, [string] Error Thrown
xhrSkipped.liveAjax Triggered when an XHR call was skipped [object] Event, [object] DataTables Settings, [string] Reason for skip (paused or processing)
setInterval.liveAjax Triggered when the polling interval was changed [object] Event, [object] DataTables Settings, [number] New interval
clearTimeout.liveAjax Triggered when the loop timeout has been cleared [object] Event, [object] DataTables Settings, [object] XHR Object
abortXhr.liveAjax Triggered when an XHR request is aborted [object] Event, [object] DataTables Settings, [object] XHR Object
setPause.liveAjax Triggered when the polling was paused or unpaused [object] Event, [object] DataTables Settings, [boolean] Pause Status
onUpdate.liveAjax Triggered when the new JSON changes were implemented [object] Event, [object] DataTables Settings, [object] Created/Deleted/Updated row data, [object] DataTable JSON data, [object] XHR Object
noUpdate.liveAjax Triggered when the the table did not need updating [object] Event, [object] DataTables Settings, [object] DataTable JSON, [object] XHR Object

LiveAjax API Methods

In addition to the already awesome DataTables API, LiveAjax comes with it’s own set of API calls. I added an API method for just about anything I could think of:

Method Description Return Parameters
iveAjax.initiate() Start XHR Polling [object] DataTables API None
iveAjax.abortXhr() Abort Current XHR request [object] DataTables API None
liveAjax.clearTimeout() Clear the polling loop [object] DataTables API [boolean] Abort current XHR request
liveAjax.xhrStatus() Retrieve latest XHR Status [object] DataTables API, [string] XHR Text status None
liveAjax.resume() Resume Updates [object] DataTables API None
liveAjax.togglePause() Toggle Pause Status [object] DataTables API None
liveAjax.pause() Pause XHR Polling [object] DataTables API None
liveAjax.isPaused() Pause XHR Polling [object] DataTables API, [boolean] Pause Status None
liveAjax.reload() Reload table DataTables API Object [function] Callback, [boolean] Reset pagination (default false), [boolean] Force through paused status
liveAjax.setInterval() Change update interval DataTables API Object [integer] New interval (use null to reset to default or config value)
Thats it! If you have any issues, I urge you to go to the issues section of the LiveAjax GIT Repo and submit any questions there.

About J

Welcome to my little corner of the InterWebs! Most of what I post on LinuxDigest is about either automation, something I find interesting, or something I just learned myself. If you want me to post an article about something, just let me know! Im more than happy to help and teach others Linux.

3 comments

  1. Hi,
    I am using DataTables Live Ajax Plugin, it is good to use, i am having one serious bug, when last json has value, and the current json has emoty value, i am getting error like below

    Uncaught TypeError: Cannot read property ‘rowId’ of undefined
    in this below line
    if ( json[ dtSettings.liveAjax.dataSrc ][0][ dtSettings.liveAjax.rowId ] === undefined ){

    help me to solve this issue

  2. Any plans to do the web socket version soon?

Leave a Reply

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

*