Add rows into table from Ajax GET

Add rows into table from Ajax GET

danbenedekdanbenedek Posts: 5Questions: 3Answers: 0

I have a table that should change data based on the selection of the user. I am using an ajax request to retrieve the data.
The table is constructed somewhat like this

opt={
columns: [{
                    name: "id",
                    render: function (data, type, full, meta) {
                        return '...'; // not important
                    },
                },
                { name: "number", },
                { name: "devicefamily", },
                ...
                ],
}
table = $('[data-datatable]').DataTable(opt)

And on ajax I do something like

$.ajax({
                    url: '...',
                    data: "{ ...}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        // data is an array with 2 objects
                        //data = JSON.parse(data);
                        table.clear();
                        table.rows.add($.map(this, function (item) {
                            return {
                                id: item.id,
                                number: item.number,
                                devicefamily: item.devicefamily,
                                ...
                            };
                        })).draw();
                    },
                    error: handleAjaxError,
                });

I have tried many things but I always get the error: "DataTables warning: table id=... - Requested unknown parameter '1' for row 0, column 1. For more information..."

What should I do In order to fill the table with the data retrieved with the ajax?

Answers

  • danbenedekdanbenedek Posts: 5Questions: 3Answers: 0

    For those interested I manage to debug and see what exactly was required in order for the add method to work
    I have changed the success callback like

    var tmp = data.map(function (item) {
                                return $.map(item, function (element, key) { return element; });
    });
    table.clear();
    table.rows.add(tmp).draw();
    

    The tmp variable is optional, I just needed to look at it to see if it was OK

  • allanallan Posts: 63,889Questions: 1Answers: 10,530 Site admin

    You want to use columns.data, not columns.name.

    The name is just used for selectors. The data value is used to tell DataTables where to get the data for that column from the data source object.

    Allan

This discussion has been closed.