Updating the DataTable using draw() not working

Updating the DataTable using draw() not working

rr98rr98 Posts: 2Questions: 1Answers: 0

Hello,

I'm getting new data for the DataTable from the server, and I'm trying to iterate over every row of the table, update the data, and then call draw() on the table to redraw it with the new data. Below is what I'm doing:

var data_json = JSON.parse(data);
var table_simulation = $('#table-simulation').DataTable()
for (var row_data of data_json.table_data) {
table_simulation.row('#tr-tsim-' + row_data.p_id).data(row_data)
}
table_simulation.draw()

But that's not working, the draw() redraws the table empty, without any data. And I've checked that row_data actually has a value on each iteration (e.g. something like {'p_id': 1, 'name': 'John'}).

What am I missing here? Thank you.

Answers

  • colincolin Posts: 12,611Questions: 0Answers: 2,154

    One thing to consider is to just load the data with Ajax originally, see example here, then you can just call ajax.reload() to udpdate.

    If that doesn't help, your code looks ok, so we'll need to see it. Information on how to create a test case (if you aren't able to link to the page you are working on) is available here.

    Cheers,

    Colin

  • rr98rr98 Posts: 2Questions: 1Answers: 0
    edited September 21

    Hi @colin,

    I'm trying to avoid using the reload() approach if I can, at least for now.

    In order for me to pass in row_data (a dictionary) to row.data(), do I need to configure some sort of mapping in the DataTable's config? I tried adding this extra config:

    columns: [
    {"data": "p_id", "name": "p_id"},
    {"data": "p_name", "name": "p_name"},
    ],

    But that didn't change anything. However, since I'm passing a dictionary to the row's data to update it, I'm wondering if I'm missing some sort of mapping somewhere so that it knows how to parse the dictionary passed in.

  • kthorngrenkthorngren Posts: 13,786Questions: 25Answers: 3,242

    If you have a dictionary/object then you will need to use columns.data.

    One problem might be the jQuery selector you are using in this statement is not finding the row:

    table_simulation.row('#tr-tsim-' + row_data.p_id).data(row_data)
    

    The best thing to do is to put together a simple test case showing an example of your table data along with a sample of the data you are trying to use to update.
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

  • kthorngrenkthorngren Posts: 13,786Questions: 25Answers: 3,242

    Also see if you are getting errors in the browser's console log.

    Kevin

Sign In or Register to comment.