Datatables cannot display my data

Datatables cannot display my data

HatimHatim Posts: 3Questions: 1Answers: 0

I ajax load my generated data using dynamically created columns, I tested for both the column and data objects, they look fine but my data still not displayed, what is wrong?

Here is the column object.

Here is the data object.

And here is the table showing nothing!

Here is the script I use:

$(document).ready(function(){
    $("#process").click(function(){
    var tableColumns = []; 
    $('#result').dataTable({
        destroy: true,
        responsive: true,
        ordering: false,
        stateSave: true,
        deferRender: true,
        ajax: {
            url: "process/",
            type: "POST",
            dataSrc: function(d) {
            heads = Object.keys(d.data[0]);
            for (var i in heads) {
                tableColumns.push({ 
                    data: heads[i],
                    title: heads[i][0].toUpperCase()+heads[i].slice(1)
                });
            }
            console.log(d.data);
            return d.data
            },
        },
        columns: tableColumns,
        layout: {
            topStart: {
                buttons: [
            {extend: 'copyHtml5', text:'<i class="fa fa-files-o"></i>', titleAttr: 'Copy'},
            {extend: 'csv', text: 'CSV'},
            {extend: 'excel', text: 'Excel'},
            {extend: 'pdf', text: 'PDF', exportOptions: {columns: ':visible'},                    
            customize: function (doc) {
            doc.defaultStyle.fontFamily = 'Arial';
            doc.defaultStyle.fontSize = 10;}},
            {extend: 'print',text: 'Print'},
            {extend: 'colvis',text: 'View'},
            {extend: 'pageLength',text: 'Length'}
            ]},
            topEnd: {
                search: {
                    placeholder: 'Type search here'
                }
            },
            bottomEnd: {
                paging: {
                    numbers: 5
                }
            }
        },
    });

});
});

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,344Questions: 26Answers: 4,954
    Answer ✓

    The problem is that ajax is an async process and the initialization options are both happening at the same time. You won't be able to build the tableColumns columns and have it applied to the columns option at the same time. See this FAQ for how this can be accomplished. Here is a simple example:
    https://live.datatables.net/huyexejo/1925/edit

    Use data to populate the table data instead of ajax.

    Kevin

Sign In or Register to comment.