Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
16
rated 0 times [  19] [ 3]  / answers: 1 / hits: 7308  / 4 Years ago, mon, december 14, 2020, 12:00:00

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


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


More From » php

 Answers
3

$_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) }
...

[#2125] Wednesday, December 9, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dusty

Total Points: 739
Total Questions: 97
Total Answers: 85

Location: Angola
Member since Wed, Apr 13, 2022
2 Years ago
;