71

I have checked several questions already about this topic here in stackoverflow, but they are all using the old dataTable. I am using DataTable. I populated my DataTable by NOT USING server side, so data are preloaded (JSON) like this :

datatable = $("#datatable").DataTable({
   data  : myData,
   moreoptions : moreoptions
});

I didn't have a problem with that, the DataTable loaded just fine. Now I want to re-populate that myData with new data i uploaded. How to reload the DataTable to reflect the changes?

Here's what I have tried so far :

$('#upload-new-data').on('click', function () {
   myData = NewlyCreatedData; // I console logged this NewlyCreatedData, and it has my uploaded data.

   datatable.draw(); // Redraw the DataTable
});

But this doesn't work. I also tried this :

datatable = $("#datatable").DataTable({
   "data"  : myData,
   "drawCallback" : function () {
      myData = NewlyCreatedData;
   },
   "moreoptions" : moreoptions,
});

Then on upload I just call the redraw trigger :

$('#upload-new-data').on('click', function () {
   datatable.draw(); // Redraw the DataTable
});

Still this doesn't work.

Gyrocode.com
  • 57,606
  • 14
  • 150
  • 185
user2881063
  • 1,049
  • 1
  • 10
  • 18

11 Answers11

82

You have to first clear the table and then add new data using row.add() function. At last step adjust also column size so that table renders correctly.

$('#upload-new-data').on('click', function () {
   datatable.clear().draw();
   datatable.rows.add(NewlyCreatedData); // Add new data
   datatable.columns.adjust().draw(); // Redraw the DataTable
});

Also if you want to find a mapping between old and new datatable API functions bookmark this

SSA
  • 5,433
  • 4
  • 36
  • 50
48

The accepted answer calls the draw function twice. I can't see why that would be needed. In fact, if your new data has the same columns as the old data, you can accomplish this in one line:

datatable.clear().rows.add(newData).draw();
Skeets
  • 4,476
  • 2
  • 41
  • 67
  • When I try this I don't get any data rendered, even though the server is returning rows. Most of my columns are rendered, some even have a dropdown. – Dean.DePue Jan 09 '18 at 17:02
  • That is strange, I've been using it successfully.... What version of DataTables are you on? I'm using 1.10.13 – Skeets Jan 09 '18 at 17:04
  • Hi Skeets - I'm using 1.10.15. – Dean.DePue Jan 09 '18 at 17:31
  • I noticed you said the server is returning rows. Are you using server side processing? This question here is just about the client side. Usually, in server-side processing, when the ajax returns with the new data, the table should be drawn automatically, so you may have some issue that is preventing the draw? – Skeets Jan 09 '18 at 17:35
  • No, I am not using server side. I call the ajax function once the page loads. – Dean.DePue Jan 09 '18 at 17:59
  • So it's a custom AJAX function, not built into Datatables? That being the case, you may need to open a new question or try one of the other answers here. It may be that this solution only works in certain cases? – Skeets Jan 09 '18 at 18:03
  • 4
    However, note that for this to work, the variable `newData` needs to be in the same format as specified here https://datatables.net/reference/api/rows.add(). I tried to use a format like this `{data: data, columns: cols, "order": [[0, "desc"]]}` and this didn't work until I passed only `{data: data}` – tsando Jan 30 '18 at 10:07
  • What if columns are changed? In my case, I need to refresh data table because of columns are either added or removed. – prisan Jun 17 '22 at 07:07
  • @prisan If you need to update the columns too, you may need to just reinitialize the whole table. I could be wrong though, it's been a while since I've worked with DataTables. You could ask a new question on StackOverflow. – Skeets Jun 20 '22 at 06:56
5

I was having same issue, and the solution was working but with some alerts and warnings so here is full solution, the key was to check for existing DataTable object or not, if yes just clear the table and add jsonData, if not just create new.

            var table;
            if ($.fn.dataTable.isDataTable('#example')) {
                table = $('#example').DataTable();
                table.clear();
                table.rows.add(jsonData).draw();
            }
            else {
                table = $('#example').DataTable({
                    "data": jsonData,
                    "deferRender": true,
                    "pageLength": 25,
                    "retrieve": true,

Versions

  • JQuery: 3.3.1
  • DataTable: 1.10.20
Sandip Bantawa
  • 2,822
  • 4
  • 31
  • 47
5

The following worked really well for me. I needed to redraw the datatable with a different subset of the data based on a parameter.

table.ajax.url('NewDataUrl?parameter=' + param).load();

If your data is static, then use this:

table.ajax.url('NewDataUrl').load();
user3101152
  • 51
  • 1
  • 2
2

Add this snippet in your jquery code to destroy, clear using datatable and also it will work for the new columns if you want to add new column each time on changes event or any other event.

if ($.fn.DataTable.isDataTable("#dataListTable")) {
        $('#dataListTable').DataTable().clear().destroy();
    }   
    $('#dataListTable').empty();

Thanks, It works for me hope work for you also

  • ** After through search, this saved my day. Cheers. ** `if(jQuery.fn.DataTable.isDataTable("#dataListTable")) { jQuery("#dataListTable").DataTable().clear();//.destroy(); jQuery("#dataListTable").empty(); } ` – John Ole Njue Jun 12 '22 at 10:11
2

I've tried to do it without workarounds, but that was my final solution:

$("#myDataTable").DataTable().clear().draw();
$("#myDataTable").DataTable().destroy();
$("#myDataTable").DataTable({    // Reinitialize it like new
    data: {},
    pagingType: "first_last_numbers",
    pageLength: -1,
    ...
});
Matheus Santz
  • 538
  • 6
  • 7
1
datatable.rows().iterator('row', function ( context, index ) {
    var data = this.row(index).data();
    var row = $(this.row(index).node());
    data[0] = 'new data';
    datatable.row(row).data(data).draw();
});
showdev
  • 28,454
  • 37
  • 55
  • 73
vlasiliy
  • 19
  • 3
1

If you want to refresh the table without adding new data then use this:

First, create the API variable of your table like this:

var myTableApi = $('#mytable').DataTable(); // D must be Capital in this.

And then use refresh code wherever you want:

myTableApi.search(jQuery('input[type="search"]').val()).draw() ;

It will search data table with current search value (even if it's blank) and refresh data,, this work even if Datatable has server-side processing enabled.

Den Pat
  • 1,118
  • 10
  • 17
1

If columns doesn't change, parameters object can be configured as function. DataTable will be updated with each value change

"ajax": {
        "url": "/warehouse/getall",
        "type": "GET",
        "dataType": "json",
        data: function (d) {
            d.storeId = document.getElementById("StoreList").value;
            d.warehouseId = document.getElementById("WarehouseList").value;
        }

StoreList and WarehouseList are user combos.

Then with each combo change DataTable is updated with current values

$("#WarehouseList").change(function () {
    $("#tblData").DataTable().ajax.reload();
});
Jaime Vasquez
  • 121
  • 1
  • 5
0

Another alternative is

dtColumns[index].visible = false/true;

To show or hide any column.

Rob Quincey
  • 2,834
  • 2
  • 38
  • 54
  • You need to use `column().visible()` if this were the method that was needed to fix the problem (https://datatables.net/reference/option/columns.visible). Additionally, if you initialize with dataTables vs DataTables, you need to make the call to the `api()`. Example: `yourdatatable.api().column(int).visible(boolean);` vs `yourdatatable.column(int).visible(boolean);` – Gwi7d31 Aug 18 '17 at 19:42
0
  1. init: var grid = $('#dataTable').DataTable({});
  2. destroy: grid.destroy();
  3. replace the content of tbody tag, eg: $('#tableBodyId').empty().append(new_data);
  4. reinit: grid = $('#dataTable').DataTable({});
TomoMiha
  • 1,218
  • 1
  • 14
  • 12