@dalton_moen
To read JSON from an AJAX POST request in PHP, you need to do the following steps:
Here's an example of how you can read the JSON data in PHP:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Read the raw POST data $jsonData = file_get_contents('php://input'); // Decode the JSON data $data = json_decode($jsonData, true); if ($data === null) { // JSON parsing error occurred http_response_code(400); // Bad Request echo json_encode(['error' => 'Invalid JSON']); exit; } // Access the data from the JSON object $name = $data['name']; $email = $data['email']; // Process the data as per your requirements // ... // Return a response $response = ['success' => true]; echo json_encode($response); |
In this example, the JSON payload is read from php://input
using the file_get_contents
function. It is then decoded using json_decode
with the second argument set to true
to convert it into an associative array.
You can then access the data from the JSON object using the appropriate keys. In the example, name
and email
are accessed from the $data
array.
Finally, you can process the data as per your requirements, and return a response using json_encode
.