Top25 Top25 - 12 days ago 5
jQuery Question

jQuery Datatable with PHP json_encode

I tried to parse database table data to jquery data table which are dynamically change. I got following output after php's

json_encode
function

$sql = "SELECT * FROM login";

$result = mysql_query($sql);
$a= array();
while ($row = mysql_fetch_assoc($result)) {
$a[][] = $row;
}

echo (json_encode($a));


Json output

[[{"id":"1","username":"test11","password":"$2y$10$NiKnEN\/ww8yGVhv3JNjSuO5FfOFSthadS2B3GcbA3KGBktAOSu6lK","role":"Administrator "}],[{"id":"2","username":"test","password":"test","role":"test"}]]


Then I called jquery data table ajax function as they said. here my coding for that

$('#example').dataTable( {
"ajax": 'ab.php'
} );


But ultimately display only "Loading..." text in the jquery data table
tbody
section. Why is that?

Answer

CAUSE

Apparently you're using DataTables version 1.10. By default, this version expects data to be in certain format, see DataTables documentation for more information.

{
    "data": [
        // row 1 data source,
        // row 2 data source,
        // etc
    ]
}

SOLUTION

Change $a[][] = $row; to $a['data'][] = $row in your PHP to produce data in the correct format.