DEV Community

Discussion on: Why PHP...???

Collapse
 
anwar_nairi profile image
Anwar • Edited

I am afraid that FormData will always convert your values to string, if it is not a Blob or a File type.

Check this StackOverflow answer, you solved your issue the right way, but I guess this has nothing to do with PHP (you would have the same issue with a NodeJS backend for instance).

Tips for your client side payload

You can take advantage of JSON.stringify to encode your data:

const response = await fetch("/fruits.php", {
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json"
  },
  method: "POST",
  body: JSON.Stringify({
    "orange": true,
    "purple": false
  })
});

Decode your payload seemlesly server side

I found this GitHub issue, with an interesting solution. I adapted it to make this seemless in your actual code:

$payload = file_get_contents('php://input');
$_POST = json_decode($payload);

var_dump($_POST["orange"]); // bool(true)
var_dump($_POST["purple"]); // bool(false)

Hope it helps!