I have an issue with jquery and datatables. I want to get the informations for the datatable from an mysql database with PHP and after that update the datatable with this informations.
I already tried it with something like this:
var datatable = $("#example").DataTable();
$.get('load_session_overview.php', function(newDataArray) {
//datatable.clear();
datatable.row.add(['Random','12','18','Menu']);
datatable.row.add([newDataArray]);
datatable.draw();
});
The first line with the add is working fine, but I don't know how to format the data in the php script correctly.
And if I'm getting more rows from the php script how can I add them all the the table?
Thanks, Phil
CodePudding user response:
One way to format the data correctly in your PHP script is to return it in a JSON format. You can use the json_encode() function in PHP to convert your data into a JSON string.
For example:
<?php
$data = array(
array('Random','12','18','Menu'),
array('Data1','13','19','Menu2'),
array('Data2','14','20','Menu3')
);
echo json_encode($data);
?>
Then, in your jQuery code, you can use the JSON.parse() method to convert the JSON string into a JavaScript object, and loop through the data to add each row to the table.
$.get('load_session_overview.php',
function(newDataArray) {
var data = JSON.parse(newDataArray);
for(var i = 0; i < data.length; i ) {
datatable.row.add(data[i]);
}
datatable.draw();
});
Alternatively, you can use ajax call and pass the data to it to load it in the datatable and also you can use the ajax call to update the datatable as well.
$.ajax({
url: "load_session_overview.php",
type: "GET",
dataType: "json",
success: function (data) {
datatable.clear();
datatable.rows.add(data);
datatable.draw();
}
});
This way you can load the data in the datatable and also update it as well.
CodePudding user response:
There are several ways to achieve this, for instance
php writes javascript code in an html script tag
see How to print JSON array inside script tag?