Correct JSON format

Correct JSON format

dydxdydx Posts: 8Questions: 3Answers: 0

So, I have a datatable whose ajax: is set to here and the datatable generates with the values as expected but when I enter JSON from my own source it gives me this error: Uncaught TypeError: Cannot read property 'length' of undefined.

My JSON looks like this:

[{
"id": "2",
"0": "2",
"name": "PO# 6549",
"1": "PO# 6549",
"price": "25",
"2": "25",
"clientid": "1",
"3": "1",
"vendorid": "1",
"4": "1",
"status": "1",
"5": "1",
"date": null,
"6": null
}, {
"id": "3",
"0": "3",
"name": "New Order",
"1": "New Order",
"price": "12",
"2": "12",
"clientid": "1",
"3": "1",
"vendorid": "1",
"4": "1",
"status": "1",
"5": "1",
"date": null,
"6": null
}]

My JS looks like this:

$(document).ready(function() {
$('#datatable').dataTable({
"ajax": 'read.php',
bAutoWidth: false
});
});

This question has an accepted answers - jump to answer

Answers

  • bindridbindrid Posts: 730Questions: 0Answers: 119

    The data in the link is an array of arrays so datatables just takes them in the order they are given.
    Your data is an array of objects so you have to map your data to columns.

    take a look at https://datatables.net/examples/ajax/objects.html it shows an example

  • dydxdydx Posts: 8Questions: 3Answers: 0

    @bindrid Got it!
    Now, there's just one issue.. How do I get this prefix: "data":[ in my JSON?
    Currently my PHP looks like this:

    public function findAll()
    {
    $result = $this->query('SELECT * FROM ' . $this->table);
    return $result->fetchAll(PDO::FETCH_ASSOC);
    }

    $designsTable = new CRUD($pdo, 'design', 'id');
    $result = $designsTable->findAll();
    echo json_encode($result);

    which generates the JSON I mentioned in my OP.
    And thanks for that help, though! Just hoping you could get me sorted on this as well =)

  • allanallan Posts: 63,455Questions: 1Answers: 10,465 Site admin
    Answer ✓

    You can use the ajax.dataSrc option set to be an empty string to tell DataTables just to read a plain array of data.

    Alternatively, in PHP you could do:

    echo json_encode( [
      "data" => $result
    ] );
    

    Allan

  • dydxdydx Posts: 8Questions: 3Answers: 0

    Thanks so much, Allan and bindrid!!!

This discussion has been closed.