Home > Software engineering >  PHP $_POST variables are null when sending FormData() in a fetch request
PHP $_POST variables are null when sending FormData() in a fetch request

Time:04-07

I am sending FormData() to a PHP script with the following JS:

async function callFetch(url, body, accept) {
    let headers = accept ? {"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8","Accept":"application/json"} : {"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"};
    let stuff ={
       method: "POST",
       credentials: "same-origin",
       mode: "same-origin",
       cache: "no-cache",
       referrerPolicy: "no-referrer",
       headers: headers,
       body: body,
    };
    console.log(stuff);
    return fetch(url, stuff).then(r => r.text());
}
let proFormData = new FormData();
proFormData.append('pID',prodID);
proFormData.append('saveProduct','1');
callFetch('script.php',proFormData,1).then(r => {
    //do stuff
    console.log(r);
});

I can see through the console, that the proFormData keys and values have been set and is sending in the fetch body.

In my PHP script I am testing the following:

<?php
echo print_r($_POST);
echo '@===@';
echo $_POST['pID'].'<- ID';
?>

Which outputs the following in my browser's console:

//What JS outputs from console.log(stuff):

Object { method: "POST", credentials: "same-origin", mode: "same-origin", cache: "no-cache", referrerPolicy: "no-referrer", headers: {…}, body: FormData }
​
body: FormData {  }
​
cache: "no-cache"
​
credentials: "same-origin"
​
headers: Object { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", Accept: "application/json" }
​
method: "POST"
​
mode: "same-origin"
​
referrerPolicy: "no-referrer"

//What PHP outputs from console.log(r):
Array
(
    [-----------------------------9849953071025538958714858089

Content-Disposition:_form-data;_name] => "pID"



33

-----------------------------9849953071025538958714858089

Content-Disposition: form-data; name="saveProduct"



1

-----------------------------9849953071025538958714858089--


)
1@===@<- ID

I'm using this exact setup for other PHP scripts and it works perfectly. However with this one specific script I am met with resistance.

I DO NOT want to send the FormData() as JSON, I wish to send it as it is, and as I have been with my other scripts.

I DO NOT want to result to the php://input workaround, as even my attempts with this method have failed.

CodePudding user response:

"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"

Don't do that. You aren't sending URL Encoded data. Let fetch infer the correct content-type from the FormData object so it doesn't lie about what it is sending. Then PHP will be able to understand the request.

  • Related