Jquery datatable add rows

Jquery datatable add rows

jtojojjtojoj Posts: 1Questions: 1Answers: 0
edited June 2022 in Free community support

I have a datatable in my page initiated like below:

var dataSet = [
    { "id": 1, "name": "Bennett Weimann", "email": "jtremblay@example.com" },
    { "id": 2, "name": "Bennett Weimann", "email": "buckridge.orin@example.com" }
];

$(document).ready(function () {
    $('#example').DataTable({
        data: dataSet,
        columns: [
            { data: 'id', title: 'Id' },
            { data: 'name', title: 'Name' },
            { data: 'email', title: 'Email' },
        ],
    });
});

Additinally I have a button which makes an ajax post reques, in the answer I get a json

[{"id":1,"name":"Bennett Weimann","email":"jtremblay@example.com"},
{"id":2,"name":"Bennett Weimann","email":"buckridge.orin@example.com"}]

If I try to add the response like below, I get an error

request.done(function (response, textStatus, jqXHR) {

        table = $('#example').DataTable();
        table.clear();
        table.rows.add(response);
        table.draw();

    });

Error is "DataTables warning: table id=example - Requested unknown parameter 'id' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4"

However if I copy and paste the response manually, it has no issue whatsoever.

request.done(function (response, textStatus, jqXHR) {

table = $('#example').DataTable();
table.clear();
table.rows.add([
    {"id":1,"name":"Bennett Weimann","email":"jtremblay@example.com"},
    {"id":2,"name":"Bennett Weimann","email":"buckridge.orin@example.com"}
]);
table.draw();

});

Any help appriciated what could cause such error.

SO link https://stackoverflow.com/questions/72750565/jquery-datatable-add-rows

Edited by Colin - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

Answers

  • colincolin Posts: 15,146Questions: 1Answers: 2,586

    I'm guessing there's something else in the response that's messing up the rows.add() call. Could you add

    console.log(JSON.stringify(response))
    

    before you add the data, and post that back. If you could link to your page please, that would also help,

    Colin

Sign In or Register to comment.