kentor
kentor

Reputation: 18534

Show loading gif when DataTable has been cleared

I have several options for my JQuery datatable which will clear the DataTable and load new data via WebSockets. Therefore I clear the Table contents with fnClearTable()and a few moments later I get the new data via my WebSocket.

This can last up to a few seconds and in the meantime I would like to display a loading image in my DataTable. How can I achieve this?

My event handler which clears the DataTable:

/* On Daterange change (e.g. Last 3 Days instead of Last 24h) */

    $('#profitList_dateRange').change(function() {
        var dateRangeHours = $("#profitList_dateRange").val();
        var jsonParamObject = JSON.parse(dateRangeHours);

        // Clear table
        var profitList = $('#profitList').dataTable();
        profitList.fnClearTable(); // Now I want to show the loading image!
        socket.emit('load-statistics', (jsonParamObject));
    });

Upvotes: 0

Views: 1298

Answers (2)

Sam Battat
Sam Battat

Reputation: 5745

Make sure you have processing: true

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

Then add:

$('.dataTables_processing', $('#example').closest('.dataTables_wrapper')).show(); 

If you want to add a GIF image you can change the markup as follows:

$('#example').dataTable({
  oLanguage: {
    sProcessing: "<img src='https://d13yacurqjgara.cloudfront.net/users/12755/screenshots/1037374/hex-loader2.gif'>"
  },
  processing: true
});

DEMO: http://jsfiddle.net/0m6uo54t/2

processing:

Enable or disable the display of a 'processing' indicator when the table is being processed (e.g. a sort). This is particularly useful for tables with large amounts of data where it can take a noticeable amount of time to sort the entries.

https://datatables.net/reference/option/processing

[UPDATE] bProcessing is the legacy option, the new DT code uses processing

Upvotes: 1

Vladimir M
Vladimir M

Reputation: 4489

One way to achieve it is if you have 2 divs (I assume that your divs are properly styled to the content inside of them):

<div id="profitList"> your table content </div>
<div id="profitListLoading"> show loading here </div>

Then in your handler:

$('#profitList_dateRange').change(function() {
        var dateRangeHours = $("#profitList_dateRange").val();
        var jsonParamObject = JSON.parse(dateRangeHours);

        // Clear table
        var profitList = $('#profitList').dataTable();
        profitList.fnClearTable(); // Now I want to show the loading image!
        $('#profitList').hide();
        $('#profitListLoading').show();
        socket.emit('load-statistics', (jsonParamObject));
    });

In your handling of loaded data you should ofc. revert the change

        $('#profitList').show();
        $('#profitListLoading').hide();

Upvotes: 1

Related Questions