arw1016
arw1016

Reputation: 17

Invalid JSON response error using JQuery DataTables with PHP & AJAX

I'm working with DataTables for the first time, and I'm running into issues actually putting the data into the table. I believe I have matched the proper JSON format that DataTables calls for using the ajax option within, however I'm still receiving an "Invalid JSON Response" error on load.

Here's my JS, I have it in a separate file called within the HTML page:

$(document).ready(function () {
  $("#copingTable").DataTable({
    "ajax": {
      "url": "overviewdata.php",
      "type": "POST",
      "dataType": "json",
      "contentType": "application/json; charset=utf-8",
      "dataSrc": "data"
    },
    "columns": [
      {"data": "FormID"},
      {"data": "SubmittedBy"},
      {"data": "Email"},
      {"data": "Date"}
    ]
  });
});

And my PHP:

$storiesSql = "SELECT FormID, CONCAT(FirstName, ' ', LastName) AS SubmittedBy, Email, DATE_FORMAT(Date, '%m/%d/%Y') AS Date FROM Stories";
  $storiesStmt = $pdo->query($storiesSql);

  $dataArray = array();

  while($row = $storiesStmt->fetch()){
    array_push($dataArray, array("FormID"=>$row['FormID'], "SubmittedBy"=>$row["SubmittedBy"], "Email"=>$row["Email"], "Date"=>$row['Date']));
  }

  echo json_encode(array("data"=>$dataArray));

This is the format of the JSON Response I receive (edited to be correct):

{"data":[{"FormID":"5e9754efc8aec","SubmittedBy":"Test Test","Email":"[email protected]","Date":"04\/15\/2020"}

Any help would be greatly appreciated!

Edit: Added in the working code with mapped data source and columns from the answer below

Upvotes: 0

Views: 1009

Answers (1)

Mostav
Mostav

Reputation: 2602

As mentioned in my comments, check the format that your PHP script output (it should be a valid json with all required fields your JS code expect), then change datatype value to 'json' value and add contentType in ...ajax.contentType field:

$(document).ready(function () {
$("#copingTable").DataTable({
    "processing": true,
    "serverSide": true,
    "ajax": {
      "url": "overview.php",
      "type": "POST",
      "dataType": "json",
      "contentType": "application/json; charset=utf-8",
      "dataSrc": ""
    }
  });
});

Upvotes: 1

Related Questions