1

I have used datatable for my website.

Now whenever I update any data for any single record I just update that row data using ajax like:

HTML is like:

<table class="datatable">
    <tr id="user_row_1">
        <td>Name 1</td>
        <td>Role 1</td>
        <td>XYZ 1</td>
    </tr>
    <tr id="user_row_2">
        <td>Name 2</td>
        <td>Role 2</td>
        <td>XYZ 2</td>
    </tr>
    <tr id="user_row_3">
        <td>Name 3</td>
        <td>Role 3</td>
        <td>XYZ 3</td>
    </tr>
</table>

Jquery is like:

oTable = $(".datatable").DataTable();
....
$("#user_row_3").html(response);

Ajax response code:

<td>Name 3 Updated</td>
<td>Role 3 Updated</td>
<td>XYZ 3 Updated</td>

Problem

but when I retrieve the data using datatable api like:

var table = $('#user-list').DataTable();
var rowData= table.row('#user_row_160').data();
$.each($(rowData),function(key,value){
    console.log(value["name"]); 
});

it returns the older data.

So how to update datatable row exactly.

1 Answer 1

4

You should always use the API, also when you change values for cells or entire rows :

table.row("#user_row_3").data(response).invalidate().draw()

DataTables have no chance to know that you have made some changes to the DOM. And DataTables does not work with two-way binding anyway, but is essentially itself a DOM-"factory" that updates the page according to a underlying set of data.

Besides that, you should never insert raw HTML, but data in the same format as you initialised the table. How you do that we dont know. If your table is a DOM table, you can sanitize response to be an array of values :

var d = $(response, 'td').map(function(i, td) {
  return td.textContent
})
table.row("#user_row_3").data(d).invalidate().draw()
Sign up to request clarification or add additional context in comments.

5 Comments

I am creating table directly using for loop and not passing any data through json or using any array. so how to pass data at the time of update row ?
@Er.KT, "I am creating table directly using for loop..." for loop of...? Could you update your question with an example? Unless you are initialising a DOM table, I cannot see any other way you could insert data but using table.row.add() with either JSON or array of strings, alternatively passing $(tr) elements ...
I have updated question, where you can see how I am appalling datatable
So I guess you have a DOM table, since you not want to be more clear :) Then just do as above -> jsfiddle.net/0f9Ljfjr/1023
I am very thankful buddy, you are great and thanks a lot for your tremendous help and spending lot of time for me

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.