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
The PHP
$_POST
variable holds the data parsed by PHP forPOST
requests withapplication/x-www-form-urlencoded
ormultipart/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: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 thenecho json_encode($myObj...
.