I am trying to send json data to server (using fetch API and PHP as a server side language). My server side code is pretty simple:
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
print_r($_POST);
?>
Now when I send the request simply with "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
like this:
fetch("http://localhost:80/test.php", {
method: 'POST',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: "a=b"
})
.then(function(response){
return response.text();
})
.then(function(text){
console.log(text);
})
Everything works fine and the output is:
Array
(
[a] => b
)
Now when I want to send the same thing but with JSON like this:
fetch("http://localhost:80/test.php", {
method: 'POST',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: JSON.stringify({"a":"b"})
})
.then(function(response){
return response.text();
})
.then(function(text){
console.log(text);
})
I get the weird output of the whole array as a key:
Array
(
[{"a":"b"}] =>
)
Now when I change the content type to: "application/json"
in fetch call, the output is completely lost and I get the empty array:
Array
(
)
Can you tell me what the reason is? and how to achieve the desired result. (sending whole data with JSON).