Hikari
Hikari

Reputation: 3947

DataTables inform load time while loading AJAX data

I have some tables that start empty and DataTables requests WebServer for the data.

It's ok to take some minutes to load it. DataTables shows default Loading message. But I'd like to add a counter informing how long the loading is running, instead of a simple Loading text or some wacky animation.

I can't find a way to do it on its documentation. Is it possible?

Update: MonkeyZeus's answer worked perfectly. Here's my final code:

// ...
,dataTablesLoading: function(e, settings, processing ){
    setTimeout(function(){
        var targetJs = e.target;
        var target = $(targetJs);
        var timerContainer = target.find('.dataTables_empty');
//tlog(targetJs,'targetJs');
//tlog(target,'target');
//tlog(timerContainer,'timerContainer');

        if(processing){
                var timer = 0;
                var timerHandler = setInterval(function(){
                    timer++;
                    var hours = Math.floor(timer/3600);
                    var minutes = Math.floor((timer-(hours*60))/60);
                    var secs = timer-(hours*3600)-(minutes*60);

                    var timerText = hours+':'+minutes.lpad("0",2)+':'+secs.lpad("0",2);
tlog(timerText,'timerText');
//tlog(timerContainer,'timerContainer');
                    timerContainer.text("Loading... "+timerText);
                },1000);


            targetJs.setAttribute("data-loading-timer",timerHandler);
tlog(timerHandler,'timerHandler processing');
        }else{
            var timerHandler = parseInt(targetJs.getAttribute("data-loading-timer"));
tlog(timerHandler,'timerHandler not processing');

            if(timerHandler>0)
                clearInterval(timerHandler);
        }

    },1000);
}
// ...
$('#...')
    .on( 'processing.dt', Framework.utils.dataTablesLoading )
    .DataTable({...})

Upvotes: 1

Views: 1628

Answers (1)

MonkeyZeus
MonkeyZeus

Reputation: 20747

First, you will need to enable processing when invoking the datatable:

$('#example').dataTable( {
    "processing": true
} );

Next, you will need to declare what happens instead of the default Loading message using the dt namespace's processing event listener:

// This event will fire twice so pay attention to the processing parameter
$('#example').on( 'processing.dt', function ( e, settings, processing ) {
    if( processing  === true ) {
        alert('Hey, we are processing!');
        // some custom code which targets #processingIndicator and applies some timer plug-in or whatever; you figure it out.
    }
    else {
        alert('Hey, we are done processing!');
        // some custom code which targets #processingIndicator and hides it; you figure it out.
    }
} )
.dataTable();

Additionally, long load times have a UX aspect to consider as well so definitely check out https://ux.stackexchange.com/a/80858/45170 if you want to make a nicer experience.

Upvotes: 1

Related Questions