I receive invalid json response although the json data is valid.

I receive invalid json response although the json data is valid.

iamkwasiiamkwasi Posts: 1Questions: 1Answers: 0
edited November 2020 in Free community support

I receive this error message:

DataTables warning: table id=candidates_grid - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1

The json returned data is valid but upon further checks, I noticed from the network (XHR) section, I see the data is displayed on the 3 row and not on the first. I am not sure what causes that, as all examples display the json returned data on the first row. So not sure if that is causing it and how I can resolve this error. The datatable displays the data but the above error shows anytime I tired to search on the name column or sort the name column.

I have attached the image and also the complete code block.
I am new to datatables. Thank you.

Below is the complete code:

$query = '';
$output = array();
$query .= "SELECT* FROM students";


if (isset($_POST["search"]["value"])) {
    $query .= 'WHERE name LIKE "%' . $_POST["search"]["value"] . '%" ';
    $query .= 'OR age LIKE "%' . $_POST["search"]["value"] . '%" ';
    
}

if (isset($_POST["order"])) {
    $query .= 'ORDER BY ' . $_POST['order']['0']['column'] . ' ' . $_POST['order']['0']['dir'] . ' ';
} else {
    $query .= 'ORDER BY id DESC ';
}
if ($_POST["length"] != -1) {
    $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $pdo->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach ($result as $row) {
    $sub_array = array();
    $sub_array[] = $row["name"];
    $sub_array[] = $row["age"];

    $sub_array[] = '<a href="details.php?id=' . $row["id"] . '" name="update" id="' . $row["id"] . '" class="btn btn-warning btn-xs update">View Details</a>';
    $sub_array[] = '<button type="button" name="delete" id="' . $row["id"] . '" class="btn btn-danger btn-xs delete">Delete</button>';
    $data[] = $sub_array;
}


$output = array(
    "draw" => intval($_POST["draw"]),
    "recordsTotal" => $filtered_rows,
    "recordsFiltered" => getAllRecords($_SESSION['username']),
    "data" => $data
);
echo json_encode($output);

Answers

  • colincolin Posts: 15,237Questions: 1Answers: 2,599

    I see the data is displayed on the 3 row and not on the first. I am not sure what causes that, as all examples display the json returned data on the first row.

    Can you post the data that is returned, please. Also, if you can link to your page, that would be helpful,

    Colin

This discussion has been closed.