Javascript:
fetch("https://localhost/data.php", {
method: "POST",
body: JSON.stringify({
data1: data1,
data2: data2
})
})
.then(res => res.json())
.then(json => function (json) {
console.log("Successful fetch.");
console.log(json);
})
.catch((error) => function (error) {
console.log("Failed to fetch. " + error);
});
data.php:
<?php
echo '{
"reply": true
}';
?>
I am trying to use a post request with fetch, but I cannot get a reply back from my PHP file, but I can access it from my browser.
>Solution :
The error is in this line .then(json => function (json) {. This code asking the then‘s callback function to return another function
fetch("https://localhost/data.php", {
method: "POST",
body: JSON.stringify({
data1: data1,
data2: data2
})
})
.then(res => res.json())
.then(json => {
console.log("Successful fetch.");
console.log(json);
})