How to read json from ajax post in php?

Member

by darion , in category: PHP General , 10 months ago

How to read json from ajax post in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 10 months ago

@darion 

To read JSON data sent via an AJAX POST request in PHP, you can use the following steps:

  1. Check if the request method is POST.
  2. Read the raw JSON data from the request body.
  3. Decode the JSON data into a PHP associative array using json_decode() function.


Here is an example code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Get the raw JSON data from the request body
    $jsonData = file_get_contents("php://input");

    // Decode the JSON data into a PHP associative array
    $data = json_decode($jsonData, true);

    // Access the data as needed
    if ($data) {
        // Access the data fields
        $name = $data['name'];
        $email = $data['email'];

        // Process the data
        // For example, output the received data
        echo "Name: " . $name . "<br>";
        echo "Email: " . $email . "<br>";
    } else {
        // JSON data could not be decoded
        echo "Error decoding JSON data";
    }
}


In this code snippet, file_get_contents("php://input") is used to get the raw JSON data from the request body. json_decode($jsonData, true) is used to decode the JSON data into a PHP associative array. You can then access the data fields as needed and process them accordingly.