Dt 'Nested object data (objects)' not working :(

Dt 'Nested object data (objects)' not working :(

drafenousdrafenous Posts: 6Questions: 2Answers: 0

Hi everyone!
I'm new user of Datatables, and i'm trying to get data by Ajax from a JSON (Web Service).

Here is a response from my WS:

{
"informacoes": {
"SP": {
"incomingCalls": 150,
"doubt": 0,
"incidents": 0,
"estado": "São Paulo"
},
"RJ": {
"incomingCalls": 6,
"doubt": 0,
"incidents": 0,
"estado": "Rio de Janeiro"
}
}

And this is my DT Function:

$('#tablesChart').DataTable({
"dom": "Bfrtip",
"buttons": ['excel', 'pdf'],
"processing": true,
"ajax": {
'url': '<?=base_url("/relatorios/auxiliar")?>',
'dataSrc': 'informacoes',
'dataType': 'json',
'error': function(response){
console.error(response.responseText);
}
},
"columns": [
{'data': '0.incomingCalls'},
{'data': '0.doubt'},
{'data': '0.incidents'},
{'data': '0.estado'}
]
});

But, when I load it in my browser, its returning: No data available in table

Gratitude to anyone who is willing to help.

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,344Questions: 26Answers: 4,954
    edited November 2018

    The problem is that Datatables expects an array of objects. You are effectively passing a single object to Datatables. This won't work . Your JSON should look more like this:

    {
        "informacoes": [{
                "incomingCalls": 150,
                "doubt": 0,
                "incidents": 0,
                "estado": "São Paulo"
            },
            {
                "incomingCalls": 6,
                "doubt": 0,
                "incidents": 0,
                "estado": "Rio de Janeiro"
            }
        ]
    }
    

    This is described here:
    https://datatables.net/manual/data/#Data-source-types

    Kevin

  • drafenousdrafenous Posts: 6Questions: 2Answers: 0

    Yes, but there is also the data function in depth, according to the link:
    https://datatables.net/examples/ajax/deep.html

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    Hi @drafenous ,

    Take a look at the ajax tab on that link you just posted - you can see it's as Kevin said, an array of objects, so that's what your server needs to return,

    Cheers,

    Colin

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

    That is true. However if you look at the Ajax tab you will see the data is in an array of objects. Each row in the Datatable is an element in the array.

    It would be best to modify the data structure in your server side code. But if that is not possible you could use ajax.dataSrc as a function to iterate the data and provide an array of objects.

    Kevin

This discussion has been closed.