Datatables – add rows with PHP


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) {

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

>Solution :

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:

$data = array(
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.

 function(newDataArray) {
  var data = JSON.parse(newDataArray);
  for(var i = 0; i < data.length; i++) {

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.

 url: "load_session_overview.php",
 type: "GET",
 dataType: "json",
 success: function (data) {

This way you can load the data in the datatable and also update it as well.

Leave a Reply Cancel reply