How to read json from ajax post in php?

by dalton_moen , in category: PHP General , a year ago

How to read json from ajax post in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by samara , a year ago

@dalton_moen 

To read JSON from an AJAX POST request in PHP, you need to do the following steps:

  1. Make sure you are sending the AJAX request with the correct content type header. Set the Content-Type header to application/json in the AJAX request.
  2. In PHP, use the php://input stream to get the raw POST data. This will contain the JSON payload sent in the AJAX request.


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.