Add data from JSON and append custom column

Add data from JSON and append custom column

vladelen-petrovvladelen-petrov Posts: 2Questions: 1Answers: 0

I add data from JSON to my 'searchResults' table with this command

$('#searchResults').dataTable().fnAddData(JSON);

Where 'JSON' is variable with JSON returned from server. It works well. But I also want to add a column (let it be some <a href>) for each row, which content doesn't return in JSON and must be added to my datatable.

Is it possible?

Datatable created like this:
$(function(){
$("#searchResults").dataTable({
"paging": true,
"ordering": false,
"info": false,
"bFilter": false,
"bLengthChange": false,
});
})

Answers

  • allanallan Posts: 62,316Questions: 1Answers: 10,226 Site admin

    Sure - use columns.defaultContent (and columns.data set to null for that column) if the content is static, or columns.render if the content is dependent on the data in the row. See also the renderer documentation.

    Allan

  • vladelen-petrovvladelen-petrov Posts: 2Questions: 1Answers: 0
    edited July 2016

    Allan, thank you!

    I also found that if I add 'columnDefs' option with needed parameters in datatable declaration, it works too:

        $(function(){
            var searchResults = $("#searchResults").DataTable({
                    "columnDefs": [ {
                        "targets": 1,
                        "data": '',
                        "defaultContent": `Additional content`
                    } ]
            });
    

    where "targets": 1 is number of column in which additional content, didn't returned inside JSON, should be placed.

    How do you think is 'columnDefs' a good alternative for 'columns'?

  • allanallan Posts: 62,316Questions: 1Answers: 10,226 Site admin

    The columnDefs documentation has information about the difference between the two. Basically use columnDefs if you don't want to have to specify something for every single column.

    Allan

This discussion has been closed.