I have this fetch method
loginbutton.onclick = (e)=> {
e.preventDefault();
var creds = {
login: login.value,
pass: pass.value
}
fetch('functions/asklogin.php', {
method: "POST",
header: {"Content-type": "application/json; charset=UTF-8"},
body: JSON.stringify(creds)
})
.then(resp => resp.text())
.then(data => console.log(data));
}
When I click, my xhr body is well fed:

But, if I try to echo these parameters from my asklogin.php
echo "no".$_POST['pass'].":".$_POST['login'];
All I get is no:
Thank you for your help
$_POST in PHP will recognize the only the form data (application/x-www-form-urlencoded or multipart/form-data) with a specified content type header.
For any other content type, you'll need to use php://input to read and parse the data.
For your case, changing the data you send through fetch should solve the issue.
...
fetch('functions/asklogin.php', {
method: "POST",
headers: {"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"},
body: Object.entries(creds).map(([k,v])=>{return k+'='+v}).join('&') // in jQuery simply use $.param(creds) instead
})
...
An alternative solution will be changing how the PHP side reads data
...
if( is_empty($_POST) ){ $_POST = json_decode(file_get_contents('php://input'), true) }
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With