skip to Main Content

I just started to learn php and want to GET/POST some data. I can send data from php to javascript, but not other way around, there is just null. What am i doing wrong?

JS:

const postData = async (data) => {
    try {
        const requestOptions = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data),
        };
        fetch('/server.php', requestOptions)
            .then(res => res.json())
            .then(data => console.log(data));
    } catch (error) {
        console.error(error);
    }
}
postData({ test: 'testData' });

PHP:

<?php
    $myObj->name = "John";
    $myObj->age = 30;
    $myObj->test = $_POST['test'];

    $myJSON = json_encode($myObj);

    echo($myJSON);
?>

The result is {name: ‘John’, age: 30, test: null}

I can see data from php which is already good for me, but i want to send there data too, so i can later work with real database.

2

Answers


  1. The PHP $_POST variable holds the data parsed by PHP for POST requests with application/x-www-form-urlencoded or multipart/form-data encoded content.

    But your JS code actually sends the data encoded as application/json in the body. This is not automatically picked up by PHP and you need to manually parse the body:

    <?php
    
    $bodyContent = file_get_contents('php://input');
    $jsonContent = json_decode($bodyContent, true);
    $testValue = $jsonContent['test'];
    
    echo $testValue;
    
    Login or Signup to reply.
  2. To get data in PHP correctly from JS you need to use file_get_contents("php://input").
    To get data in JS correctly from a PHP response, set the headers application/json in PHP and then echo json_encode($myObj....

    $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
    $decoded = [];
    if ($contentType === "application/json" || $contentType === "application/x-www-form-urlencoded") {
        $content = trim(file_get_contents("php://input"));
        $decoded = json_decode($content, true);
    }else{
        $decoded = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
    }
    
    $myObj->name = "John";
    $myObj->age = 30;
    $myObj->test = $decoded['test'];
    
    header("ContentType: application/json");
    echo json_encode($myObj, JSON_HEX_QUOT | JSON_HEX_TAG);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search