Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

js fetch post works, but php is empty [duplicate]

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:

enter image description here

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

like image 929
Richard Avatar asked Mar 21 '26 01:03

Richard


1 Answers

$_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) }
...
like image 99
HymnZzy Avatar answered Mar 23 '26 13:03

HymnZzy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!