I am trying to fill a responsive datatable with an AJAX request to a PHP script, the response is returned in JSON_encode format, I can see the response in the XHR requests:
["abc","def","ght","jkl"]
Here is the code I am using:
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
</tr>
</tfoot>
</table>
$('#dataTables-example').DataTable({
responsive: true,
"ajax": "search_autocomplete.php",
});
Here is the PHP script:
if ($result->num_rows >0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$list[] =$row['name'];
}
echo json_encode( $list );
}
When you want to insert an array datasource, i.e not object literals, the source must be an array of arrays :
[["abc"],["def"],["ght"],["jkl"]]
$('#dataTables-example').DataTable({
"ajax": {
url: "search_autocomplete.php",
dataSrc: ''
}
});
if ($result->num_rows >0) {
while($row = $result->fetch_assoc()) {
$list[] = array($row['name']); //<----
}
echo json_encode($list);
}
That is also the case if you use Jonathans suggestion, json_encode( array(data => $list)) - you would still need to wrap each item into an array, otherwise you get the a, d, g etc because dataTables access each string as the array it expects, each character is treated as an array item, data for a column.
if ($result->num_rows >0) {
while($row = $result->fetch_assoc()) {
$list[] = array($row['name']); //<----
}
echo json_encode(array('data' => $list));
}
$('#dataTables-example').DataTable({
"ajax": "search_autocomplete.php"
});
When using just a string value, at least, DataTables's ajax option expects the response to be wrapped in another object:
Note that DataTables expects the table data to be an array of items in the
dataparameter of the object ...{ "data": [ // row 1 data source, // row 2 data source, // etc ] }
To get this, you can wrap the $list in another array() before encoding:
echo json_encode( array( data => $list ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With