DataTable().ajax.reload() not reloading table

687 views Asked by At

I am populating rows into table body by using jQuery append function this works fine, but when I try to search any data from table then the table gets cleared.

Here is my code.

for (i = 0; i < mapping.length; i++) {
    var tr = $('<tr>' + '<td>' + ' <input type="checkbox" '
            + ' onchange="selectItem(this);" '
            + (mapping[i]['selected'] == true ? "checked" : "")
            + ' data-el_id="' + mapping[i]['id'] + '">'
            + ' </td>' + ' <td>' + mapping[i]['name'] + ' </td>'
            + ' <td>' + mapping[i]['itemName'] + ' </td>' + ' <td>'
            + mapping[i]['url'] + ' </td>' + ' </tr>');
    $("#tableBody").append(tr);
}
2

There are 2 answers

1
davidkonrad On BEST ANSWER

You need to go through the dataTables API in order to insert rows. I guess your data items looks like this :

{
    "selected": true,
    "id": 42,
    "name": "test",
    "itemName": "item"
}

Then, if you initialise your table like this :

var table = $('#example').DataTable({
    columns : [
        { data: 'selected',
          render: function (data, type, full, meta) {
              var input = '<input type="checkbox" onchange="selectItem(this);" ';
              input += data == true ? "checked" : "";
              input += ' data-el_id="' + full.id + '">';
              return input
          }
        },
        { data: 'name' },
        { data: 'itemName' }
    ]
});

You can insert all the rows in a loop :

for (i = 0; i < mapping.length; i++) {
   table.row.add(mapping[i]).draw();
}

small demo -> http://jsfiddle.net/fu0r4oba/

0
Ivanka Todorova On

You should use DataTable.row.add(). Example:

$yourDataTables.row.add([
counter + '.1',
counter + '.2',
counter + '.3',
counter + '.4',
counter + '.5']).draw();