6

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

Richard
  • 994
  • 7
  • 26
  • What is the result when you `var_dump($_POST)`? – Urmat Zhenaliev Dec 14 '20 at 14:15
  • This should help you out - https://stackoverflow.com/q/8893574/4287624 – HymnZzy Dec 14 '20 at 14:18
  • @UrmatZhenaliev empty array – Richard Dec 14 '20 at 14:19
  • 1
    @Richard .. in short, for `$_POST` to work you need to send the data as form data along with a respective content-type. If you send json data then you need to use `php://input` to read the posted data. – HymnZzy Dec 14 '20 at 14:24
  • 1
    Sorry guys, I should have mentioned that I am aware that the stream is feed (but I thought it was explicit since I've post a screenshot of it). Thanks anyway @HymnZzy yes, but how do you pass data as a classic form within fetch api? I can't find the right syntax in the api doc – Richard Dec 14 '20 at 14:29
  • `body: Object.entries(creds).map(([k,v])=>{return k+'='+v}).join('&')` and set content-type as `application/x-www-form-urlencoded` – HymnZzy Dec 14 '20 at 14:38
  • 1
    You can do as HymnZzy said but it's probably simpler (and less brittle) just to change the way PHP reads the data. – ADyson Dec 14 '20 at 14:43

1 Answers1

19

$_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) }
...
HymnZzy
  • 2,669
  • 1
  • 17
  • 27