Chelseawillrecover
Chelseawillrecover

Reputation: 2644

Auto refresh DataTables table with reloading the whole page

Is anyone able to guide on how to refresh datatables datas in every 1min interval without reloading the entire page.

This is my code:

$(document).ready( function () {
           var refreshTable = $('#id_css').DataTable({
                "sAjaxSource": 'ajax/alert_data.txt',
                "bServerSide": true,
                "iDisplayLength": 100,
                "bFilter": false,
                "aaSorting" : [[2, "desc"]],
                "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                    if ( aData[2] == "5" )
                    {
                        $('td', nRow).css('background-color', 'Red');
                    }
                    else if ( aData[2] == "4" )
                    {
                        $('td', nRow).css('background-color', 'Orange');
                    }
                 }

              });
setInterval (function test() {
refreshTable.fnDraw();
}, 1000);
 });

I have tried using this plugin fnReloadAjax.js but keep getting TypeError: refreshTable.fnReloadAjax is not a function. This is how I used it:

setInterval (function test() {
refreshTable.fnReloadAjax();
}, 1000);

and i have also added its cdn

<script src="//cdn.datatables.net/plug-ins/725b2a2115b/api/fnReloadAjax.js"></script>

Any assistance or guide will be much appreciated.

Upvotes: 0

Views: 8188

Answers (2)

Chelseawillrecover
Chelseawillrecover

Reputation: 2644

Its strange that changing the DataTable to dataTable was the root cause of this failing the whole time. That is small d instead of capital D, really annoying...

$(document).ready( function () {
       var refreshTable = $('#id_css').dataTable({
            "sAjaxSource": 'ajax/alert_data.txt',

Upvotes: 0

user3118321
user3118321

Reputation:

You could do

var refreshTable = $('#id_css').DataTable({ ...

Then within the document.ready function (has to be in the scope otherwise fnDraw won't work) you use:

setInterval (function test() {
    refreshTable.fnDraw();
}, 1000);

There is a scope issue, the code should look like this:

$(document).ready( function () {
       var refreshTable = $('#id_css').DataTable({
            "sAjaxSource": 'ajax/alert_data.txt',
            "bServerSide": true,
            "iDisplayLength": 100,
            "bFilter": false,
            "aaSorting" : [[2, "desc"]],
            "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                if ( aData[2] == "5" )
                {
                    $('td', nRow).css('background-color', 'Red');
                }
                else if ( aData[2] == "4" )
                {
                    $('td', nRow).css('background-color', 'Orange');
                }
             }   
       });
       setInterval (function test() {
         refreshTable.fnDraw();
       }, 1000);
 });

Upvotes: 1

Related Questions