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.

11 Answers 11

81

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

0
46

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();
9
  • 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 9, 2018 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 9, 2018 at 17:04
  • Hi Skeets - I'm using 1.10.15.
    – Dean.DePue
    Jan 9, 2018 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 9, 2018 at 17:35
  • 4
    However, note that for this to work, the variable newData needs to be in the same format as specified here 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, 2018 at 10:07
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();
1
  • This was the simplest solution - and it works great. Thanks.
    – FontFamily
    Jul 15, 2021 at 23:13
4

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
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

1
  • ** After through search, this saved my day. Cheers. ** if(jQuery.fn.DataTable.isDataTable("#dataListTable")) { jQuery("#dataListTable").DataTable().clear();//.destroy(); jQuery("#dataListTable").empty(); } Jun 12, 2022 at 10:11
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();
});
1
  • 2
    What was the problem and how does your code solve it?
    – showdev
    Aug 16, 2016 at 15:57
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.

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();
});
1

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,
    ...
});
0

Another alternative is

dtColumns[index].visible = false/true;

To show or hide any column.

1
  • You need to use column().visible() if this were the method that was needed to fix the problem (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, 2017 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({});
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.