Reputation: 209
I have a datatable js and I fill in with ajax (json), in my json, its return is several entries, I see this through the console, but, the datatable is only populated with the first json record.
My Code
$(document).ready(function()
{
$.ajax({
type : 'POST',
url : 'view/list/clients_1.php',
dataType: 'json',
cache: false,
success : function(result)
{
//pass data to datatable
console.log(result); // just to see I'm getting the correct data.
$('#my_table').DataTable({
"searching": false, //this is disabled because I have a custom search.
"bAutoWidth": false,
"bFilter": true,
"bLengthChange": false,
"responsive": true,
"aaData": [result], //here we get the array data from the ajax call.
"aoColumns": [
{ "sTitle": "#" },
{ "sTitle": "Name" },
{ "sTitle": "Work" }
]
});
}
});
Code of file: clients_1.php
$clients_sql =
"
SELECT
*
FROM
client
";
$result = mysqli_query($mysqli, $clients_sql);
$dataArray = array();
while( $row = mysqli_fetch_array($result) )
{
$dataArray[] = $row["client_id"];
$dataArray[] = $row["client_name"];
$dataArray[] = $row["client_work"];
}
echo json_encode($dataArray);
Upvotes: 1
Views: 180
Reputation: 67
I recommend adding to the answer given by sNniffer
$data = [];
just above the while loop.
Otherwise, when there are no rows in the query (and the while loop is not executed), you get this warning from datatables
Upvotes: 0
Reputation: 209
resolved
var table = $('#my_table').dataTable({
serverSide: true,
searching: false,
bAutoWidth:false,
bFilter: true,
bLengthChange: false,
responsive: true,
ajax: "view/lista/clientes_1.php",
dataSrc: 'data',
columns: [
{sTitle: "#", data: 'client_id' },
{sTitle: "Name", data: 'client_nome' },
{sTitle: "Work", data: 'client_work' }
]
}); // End: DataTable
$('#search-table').unbind();
$('#search-table').bind('keyup', function(e) {
//if(e.keyCode == 13) {
table.fnFilter(this.value);
// }
});
PHP
$result = mysqli_query($mysqli, $clients_sql);
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$data[] = $row;
}
$results = [
"sEcho" => 1,
"iTotalRecords" => count($data),
"iTotalDisplayRecords" => count($data),
"aaData" => $data
];
echo json_encode($results);
Upvotes: 1