115

I am trying to implement functionality whereby clicking a button on the screen will cause my jQuery dataTable to refresh (as the server-side data source may have changed since the dataTable was created).

Here's what I have:

$(document).ready(function() {
    $("#my-button").click(function() {
        $("#my-datatable").dataTable().fnReloadAjax();
    });
});

But when I run this, it does nothing. What's the proper way to refresh the dataTable when the button is clicked?

cottontail
  • 10,268
  • 18
  • 50
  • 51
IAmYourFaja
  • 55,468
  • 181
  • 466
  • 756

26 Answers26

185

With version 1.10.0 of DataTables, it is built-in and easy:

var table = $('#example').DataTable();
table.ajax.reload();

or just

$('#example').DataTable().ajax.reload();

http://datatables.net/reference/api/ajax.reload()

Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43
atmelino
  • 2,887
  • 2
  • 20
  • 15
  • 30
    Be careful and use `$('#example').DataTable()` and not `$('#example').dataTable()`. – Sergiu May 04 '15 at 16:10
  • After I do this I cannot access the content of the datatable. It then says I only have 2 TR's (one with the headers, and one with only 1 cell displaying there is no data). Do I have to redraw it first? – Jon Koeter May 15 '15 at 10:25
  • Jon Koeter: impossible to answer your question without seeing your code. Please post as a new question along with your code to allow reproducing the problem. – atmelino May 16 '15 at 23:47
  • This can throw an error `cannot reinitialise datatable jquery`. This happens because `table` was initialised again and again for each entry of the table. To avoid this, make sure you initialise `table ` just once. – Shubham A. Jul 03 '16 at 05:12
  • 6
    To preserve the paging info use. table.ajax.reload(null,false), as mentioned in official documentation here https://datatables.net/reference/api/ajax.reload() – Srinivas Rathikrindi Sep 14 '16 at 09:22
  • 2
    This does nothing except give me the error `Cannot set property 'data' of null` – Cerin Oct 14 '20 at 17:51
  • What is '#example'? Is it the id of the table element? – Hosein Aqajani Nov 22 '20 at 14:31
  • It do not work when the source is a SharePoint list. – Muhammad Zeeshan Tahir Mar 03 '22 at 20:51
47

Destroy the datatable first and then draw the datatable.

$('#table1').DataTable().destroy();
$('#table1').find('tbody').append("<tr><td><value1></td><td><value1></td></tr>");
$('#table1').DataTable().draw();
jcoder
  • 227
  • 3
  • 14
36

You could use an extensive API of DataTable to reload it by ajax.reload()

If you declare your datatable as DataTable() (new version) you need:

var oTable = $('#filtertable_data').DataTable( );
// to reload
oTable.ajax.reload();

If you declare your datatable as dataTable() (old version) you need:

var oTable = $('#filtertable_data').dataTable( );
// to reload
oTable.api().ajax.reload();
Sruit A.Suk
  • 7,073
  • 7
  • 61
  • 71
34

You can try the following:

function InitOverviewDataTable() {
    oOverviewTable = $('#HelpdeskOverview').dataTable({
        "bPaginate": true,
        "bJQueryUI": true, // ThemeRoller-stöd
        "bLengthChange": false,
        "bFilter": false,
        "bSort": false,
        "bInfo": true,
        "bAutoWidth": true,
        "bProcessing": true,
        "iDisplayLength": 10,
        "sAjaxSource": '/Helpdesk/ActiveCases/noacceptancetest'
    });
}

function RefreshTable(tableId, urlData) {
    $.getJSON(urlData, null, function(json) {
        table = $(tableId).dataTable();
        oSettings = table.fnSettings();

        table.fnClearTable(this);

        for (var i = 0; i < json.aaData.length; i++) {
            table.oApi._fnAddData(oSettings, json.aaData[i]);
        }

        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
        table.fnDraw();
    });
}
// Edited by Prasad
function AutoReload() {
    RefreshTable('#HelpdeskOverview', '/Helpdesk/ActiveCases/noacceptancetest');

    setTimeout(function() {
        AutoReload();
    }, 30000);
}

$(document).ready(function() {
    InitOverviewDataTable();
    setTimeout(function() {
        AutoReload();
    }, 30000);
});

http://www.meadow.se/wordpress/?p=536

julianstark999
  • 3,450
  • 1
  • 27
  • 41
Xavier
  • 1,672
  • 5
  • 27
  • 46
  • This is great! But I found you are calling the `_fnAddData`, which is supposed as a private function only. Is this risky? Let's say in the future the function signature might be changed. – Roy Ling Nov 16 '12 at 13:24
33

I had the same problem, this is how i fixed it:

first get the data with method of your choice, i use ajax after submitting results that will make change to the table. Then clear and add fresh data:

var refreshedDataFromTheServer = getDataFromServer();

var myTable = $('#tableId').DataTable();
myTable.clear().rows.add(refreshedDataFromTheServer).draw();

here is the source: https://datatables.net/reference/api/clear()

Mosd
  • 1,640
  • 19
  • 22
21

This simple answer worked for me

                  $('#my-datatable').DataTable().ajax.reload();

ref https://datatables.net/forums/discussion/38969/reload-refresh-table-after-event

Stephen Ngethe
  • 1,034
  • 13
  • 24
18

i would recommend using the following code.

table.ajax.reload(null, false); 

The reason for this, user paging will not be reset on reload.
Example:

<button id='refresh'> Refresh </button>

<script>
    $(document).ready(function() {

        table = $("#my-datatable").DataTable();
        $("#refresh").on("click", function () { 
         table.ajax.reload(null, false); 
        });

   });
</script>

detail about this can be found at Here

Ad Kahn
  • 551
  • 4
  • 6
13
var ref = $('#example').DataTable();
ref.ajax.reload();

If you want to add a reload/refresh button to DataTables 1.10 then use drawCallback.

See example below (I am using DataTables with bootstrap css)

var ref= $('#hldy_tbl').DataTable({
        "responsive": true,
        "processing":true,
        "serverSide":true,
        "ajax":{
            "url":"get_hotels.php",
            "type":"POST"
        },
        "drawCallback": function( settings ) {
            $('<li><a onclick="refresh_tab()" class="fa fa-refresh"></a></li>').prependTo('div.dataTables_paginate ul.pagination');
        }
    });

function refresh_tab(){
    ref.ajax.reload();
}
blackandorangecat
  • 1,246
  • 5
  • 18
  • 37
Vibin TV
  • 822
  • 9
  • 28
7

Use this code ,when you want to refresh your datatable:

 $("#my-button").click(function() {
    $('#my-datatable').DataTable().clear().draw();
 });
AdagioDev
  • 556
  • 5
  • 12
4

Try destroy datatable first then setup it again, example

var table;
$(document).ready(function() {
    table = $("#my-datatable").datatable()
    $("#my-button").click(function() {
        table.fnDestroy();
        table = $("#my-datatable").dataTable();
    });
});
Nick Hoàng
  • 417
  • 2
  • 6
3

This is how I do it... Maybe not the best way, but it's definitely simpler (IMHO) and doesn't require any additional plugins.

HTML

<div id="my-datatable"></div>

jQuery

function LoadData() {
    var myDataTable = $("#my-datatable").html("<table><thead></thead><tbody></tbody></table>");
    $("table",myDataTable).dataTable({...});
}
$(document).ready(function() {
    $("#my-button").click(LoadData);
    LoadData();
});

Note: In my workings with jQuery dataTable, sometimes if you don't have <thead></thead><tbody></tbody> it doesn't work. But you might be able to get by without it. I haven't exactly figured out what makes it required and what doesn't.

Drew Chapin
  • 7,779
  • 5
  • 58
  • 84
3

If you use the url attribute, just do

table.ajax.reload()
cottontail
  • 10,268
  • 18
  • 50
  • 51
Herman Demsong
  • 321
  • 3
  • 7
2

well, you didn't show how/where you are loading the scripts, but to use the plug-in API functions, you have to include it in your page after you load the DataTables library but before you initialize the DataTable.

like this

<script type="text/javascript" src="jquery.dataTables.js"></script>
<script type="text/javascript" src="dataTables.fnReloadAjax.js"></script>
RASG
  • 5,988
  • 4
  • 26
  • 47
2
var myTable = $('#tblIdName').DataTable();
    myTable.clear().rows.add(myTable.data).draw();

This worked for me without using ajax.

cottontail
  • 10,268
  • 18
  • 50
  • 51
1

Allan Jardine’s DataTables is a very powerful and slick jQuery plugin for displaying tabular data. It has many features and can do most of what you might want. One thing that’s curiously difficult though, is how to refresh the contents in a simple way, so I for my own reference, and possibly for the benefit of others as well, here’s a complete example of one way if doing this:

HTML

<table id="HelpdeskOverview">
  <thead>
    <tr>
      <th>Ärende</th>
      <th>Rapporterad</th>
      <th>Syst/Utr/Appl</th>
      <th>Prio</th>
      <th>Rubrik</th>
      <th>Status</th>
      <th>Ägare</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

Javascript

function InitOverviewDataTable()
{
  oOverviewTable =$('#HelpdeskOverview').dataTable(
  {
    "bPaginate": true,
    "bJQueryUI": true,  // ThemeRoller-stöd
    "bLengthChange": false,
    "bFilter": false,
    "bSort": false,
    "bInfo": true,
    "bAutoWidth": true,
    "bProcessing": true,
    "iDisplayLength": 10,
    "sAjaxSource": '/Helpdesk/ActiveCases/noacceptancetest'
  });
}

function RefreshTable(tableId, urlData)
{
  $.getJSON(urlData, null, function( json )
  {
    table = $(tableId).dataTable();
    oSettings = table.fnSettings();
    
    table.fnClearTable(this);

    for (var i=0; i<json.aaData.length; i++)
    {
      table.oApi._fnAddData(oSettings, json.aaData[i]);
    }

    oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
    table.fnDraw();
  });
}

function AutoReload()
{
  RefreshTable('#HelpdeskOverview', '/Helpdesk/ActiveCases/noacceptancetest');
 
  setTimeout(function(){AutoReload();}, 30000);
}

$(document).ready(function () {
  InitOverviewDataTable();
  setTimeout(function(){AutoReload();}, 30000);
});

Source

cottontail
  • 10,268
  • 18
  • 50
  • 51
Michel Ayres
  • 5,891
  • 10
  • 63
  • 97
1

you have to write this line of code after doing update operation.

$('#example').DataTable().ajax.reload();
cottontail
  • 10,268
  • 18
  • 50
  • 51
Manthan Patel
  • 1,784
  • 19
  • 23
0
if(data.length==0){
    alert("empty");
      $('#MembershipTable > tbody').empty();
    // $('#MembershipTable').dataTable().fnDestroy();
            $('#MembershipTable_info').empty(); 
            $("#MembershipTable_length").empty();
            $("#MembershipTable_paginate").empty();

     html="<tr><td colspan='20'><b>No data available in Table</b> </td></tr>";
   $("#MembershipTable").append(html);
}

else{
     $('#MembershipTable').dataTable().fnDestroy();
    $('#MembershipTable > tbody').empty();

 for(var i=0; i<data.length; i++){
    //
.......}
cottontail
  • 10,268
  • 18
  • 50
  • 51
0

According to the DataTable help, I could done for my table.

I want wanted multiple database to my DataTable.

For example: data_1.json > 2500 records - data_2.json > 300 records - data_3.json > 10265 records

var table;
var isTableCreated= false;

if (isTableCreated==true) {
    table.destroy();
    $('#Table').empty(); // empty in case the columns change
}
else
    i++;

table = $('#Table').DataTable({
        "processing": true,
        "serverSide": true,
        "ordering": false,
        "searching": false,
        "ajax": {
            "url": 'url',
            "type": "POST",
            "draw": 1,
            "data": function (data) {
                data.pageNumber = (data.start / data.length);
            },
            "dataFilter": function (data) {
                return JSON.stringify(data);
            },
            "dataSrc": function (data) {
                if (data.length > 0) {
                    data.recordsTotal = data[0].result_count;
                    data.recordsFiltered = data[0].result_count;
                    return data;
                }
                else
                    return "";
            },

            "error": function (xhr, error, thrown) {
                alert(thrown.message)
            }
        },
        columns: [
           { data: 'column_1' },
           { data: 'column_2' },
           { data: 'column_3' },
           { data: 'column_4' },
           { data: 'column_5' }
        ]
    });
Community
  • 1
  • 1
0

if using datatable v1.10.12 then simply calling .draw() method and passing your required draw types ie full-reset, page then you will re-draw your dt with new data

let dt = $("#my-datatable").datatable()

// do some action

dt.draw('full-reset')

for more check out datatable docs

Jimmy Obonyo Abor
  • 7,335
  • 10
  • 43
  • 71
0

I had done something that relates to this... Below is a sample javascript with what you need. There is a demo on this here: http://codersfolder.com/2016/07/crud-with-php-mysqli-bootstrap-datatables-jquery-plugin/

//global the manage member table 
var manageMemberTable;

function updateMember(id = null) {
    if(id) {
        // click on update button
        $("#updatebutton").unbind('click').bind('click', function() {
            $.ajax({
                url: 'webdesign_action/update.php',
                type: 'post',
                data: {member_id : id},
                dataType: 'json',
                success:function(response) {
                    if(response.success == true) {                      
                        $(".removeMessages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
                              '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                              '<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
                            '</div>');

                        // refresh the table

                        manageMemberTable.ajax.reload();

                        // close the modal
                        $("#updateModal").modal('hide');

                    } else {
                        $(".removeMessages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
                              '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                              '<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
                            '</div>');

                        // refresh the table                        
                        manageMemberTable.ajax.reload();

                        // close the modal
                        $("#updateModal").modal('hide');
                    }
                }
            });
        }); // click remove btn
    } else {
        alert('Error: Refresh the page again');
    }
}
Mwangi Thiga
  • 1,339
  • 18
  • 22
0

For my case (DataTables 1.10.7) following code works for me;


let table = $(tableName).DataTable();
table.clear().draw();

$(tableName).dataTable({ ... });

Datatables clear(): Simply remove all rows of data from the table

AbdurrahmanY
  • 809
  • 13
  • 22
0

Very Simple answer

$("#table_name").DataTable().ajax.reload(null, false); 
Arunraj S
  • 758
  • 7
  • 26
0

My table first call:

var myTable = $('.myTable').DataTable({
    "language": {
        "url": "//cdn.datatables.net/plug-ins/1.11.0/i18n/es_es.json"
    },
    dom: 'Bfrtip',
    processing: true,
    "paging": false
});

Your ajax call code here.

Then after the ajax result:

//Destroy my table
myTable.destroy();

//Place my table again
$("#tableWrapper").html(''+
    '<table class="table-striped myTable">'+
        '<thead>'+
            '<tr>'+
                '<th>Title</th>'+
            '</tr>'+
        '</thead>'+
        '<tbody id="info_conds">'+
            '<td>Content</td>'+
        '</tbody>'+
    '</table>'+
'');

Calling my table properties again

myTable = $('.myTable').DataTable({
    "language": {
        "url": "//cdn.datatables.net/plug-ins/1.11.0/i18n/es_es.json"
    },
    dom: 'Bfrtip',
    processing: true,
    "paging": false
});

Done.

0

This is what has fixed this issue for me:

const myTable= $('#mytable');
myTable.DataTable({
  **bDestroy: true**
}
);
answerSeeker
  • 2,692
  • 4
  • 38
  • 76
-2
function autoRefresh(){
    table.ajax.reload(null,false); 
    alert('Refresh');//for test, uncomment
}

setInterval('autoRefresh()', 5000);
cottontail
  • 10,268
  • 18
  • 50
  • 51
-6

reinitialise datatable with init and write retrieve as true ..done..so simple

eg.

TableAjax.init();
retrieve: true,
Johan
  • 8,068
  • 1
  • 33
  • 46