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.
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
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);
I hope someone will find this answer. I am using Codeigniter 3.1.11 and I've found the answers after getting help from a friend.
Controller
class YourController extends CI_Controller
{
public function yourMethod() {
// THIS CODE IS A MUST!
$input = json_decode(file_get_contents('php://input'), true);
// You get the data you sent via FETCH
var_dump($this->input->post('testdata'));
}
}
FETCH POST JAVASCRIPT
let postData = new FormData();
postData.append('testdata', 123);
fetch('http://localhost/your-app-name/yourcontroller/yourMethod', {
method: 'POST',
mode: 'no-cors',
headers: {
"Content-Type": "application/json"
},
body: postData
}).then((res) => {
console.log(res);
}).catch(console.log);
To view the preview of the data you send or get using Fetch you can inspect, go to tab Network, in the table "Name", click yourMethod then go to tab "Preview". In the preview you can see 123.