EDIT: I’ve updated my code due to feedback from here, and it’s no longer giving me an empty array but now it’s simply giving me null.
EDIT 2: Someone in my organization solved this for me! Turns out I was using POST options that I didn’t need. My working code is:
Frontend:
$.ajax({
type: "POST",
url: "update_data_ajax.php",
data: {
events: JSON.stringify(currentEventsRows)
}
}).done(function(data) {
console.log("Done");
console.log(data);
});
Backend:
echo json_encode($_POST);
Original post:
I’m trying to make an AJAX POST request to post some data to a SQL table, but it doesn’t seem like my POST request is actually sending anything because the PHP backend is simply giving me a null.
To try to narrow down the problem, I simplified my page down to a JavaScript frontend that posts an array of data and a PHP backend that simply returns the data. Here’s the relevant part of my frontend webpage (update_data.php):
let currentEventsRows = [/* array of dicts of strings */];
$.ajax({
method: "POST",
url: "update_data_ajax.php",
contentType: "application/json; charset=utf-8",
dataType: "JSON",
data: JSON.stringify{
events: currentEventsRows
},
processData: false
}).done(function(data) {
console.log("Done");
console.log(data);
});
Here’s my PHP backend (update_data_ajax.php):
<?php
$_POST = json_decode(file_get_contents("php://input"), true);
echo $_POST;
?>
And here’s the console output:
Done
null
What am I doing wrong? I feel like I’m missing something totally simple.
2
Answers
Someone from my organization actually solved this for me. Turns out I was using POST options that I didn't need.
Frontend:
Backend:
You have 2 issues here, 1. You aren’t sending the JSON properly. 2. You’re not reading the JSON properly.
You have to encode your JSON to send in your ajax call
Your JSON data is not populated in the $_post superglobal(this only happens for multipart/form-data and application/x-www-form-urlencoded), so you have to read it from
php://input