I'm trying Fetch API for the first time and I have problems sending POST data to a PHP server.
I'm moving away from $.ajax and trying pure javascript solutions to communicate with different servers (sometimes local, sometimes not). Now I'm trying to understand Fetch API and, even if it's simple and intuitive, I've stumbled on a weird and unexpected problem:
I CAN'T send JSON post to PHP server
I CAN send form-data post to LOCAL PHP
I CAN'T send form-data post to WEB URL PHP
I can (obviously) retrieve data from all the above, but strangely nothing arrives.
Through $_SERVER['REQUEST_METHOD'] I can see that when using the LOCAL path I get "POST" as I asked, but when using the WEB URL it changes in GET for some reason I don't understand.
url="/";
url="www.something.com";
fetch(url, {
method: 'POST',
body: JSON.stringify({
test: "toast",
})
})
.then(function(response) {
return response.text();
})
.then(function(data) {
console.log(data);
});
I expect just to send and receive data in a solid and clear way. No jquery, no libraries, etc.
I just want to send a JSON {"test":"toast"} and find it on the PHP file when checking the $_POST var.
UPDATE
It seems that the problem with local and web urls were on this difference: www.something.com/test => www.something.com/test/index.php. Without index.php for some reason it refused the POST data (but read the echoed info anyway). But the problem about JSON remain.
I CAN'T send JSON post to PHP
I CAN send form-data post to PHP
UPDATE
I found that $_POST and $_GET don't work well with Fetch API. You have to use php://input to get all the data sent to the server.
Don't know why. There's a better solution? Why ajax and XMLHttpRequest don't have this kind of problems?
Note: If you want the data to be recognized as json, you have to specify it with a header, even this was never requested so why now? Is Fetch API missing something?
header('Content-Type: application/json');
$test=json_decode(file_get_contents("php://input"));
//some code
echo json_encode($test);