Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FormData object always empty

I am trying to create form data to send within a post request (to a PHP script) with FormData.

However, the FormData object is always empty:

var oReq = new XMLHttpRequest();
var url = "http://www.test.com/test.php";
oReq.open("POST", url, true);
oReq.setRequestHeader("Content-Type","multipart/form-data");
var myFormData = new FormData();
myFormData.append("formType","PDF");
myFormData.append("pdf", pdf.output(),"thisPDF.pdf");
oReq.send(myFormData);

the 'pdf' variable is a jsPDF object (I've checked that it is a valid object and I have tried to remove that line and only have the "test" form data element sent. Yet, myFormData is always an empty object. Hoping I'm just missing something simple here.

In addition, when I try to check for the existence of the form elements in the PHP script, it shows no $_POST and no $_FILE elements at all.

ADDITIONAL INFO:

When I try this code:

var oReq = new XMLHttpRequest();
var url = "http://www.test.com/test.php";
oReq.open("POST", url, true);
oReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
var myFormData = new FormData();
myFormData.append("formType","PDF");
alert(JSON.stringify(myFormData));
oReq.send(myFormData);

I can then access the "formType" $_POST variable in the php script. But if I add in the File append statement to the myFormData object (and keep the same 'Content-Type', the PHP script errors returning a "not allowed access" error.

However, the $_POST is set according to isset($_POST) in both cases and with the file inserted the $_FILE variable is set according to isset($_FILE).

like image 889
Michael Reiland Avatar asked Nov 09 '22 16:11

Michael Reiland


1 Answers

Remove the oReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); from the code. Browser automatically set multipart/form-data header, if you add file in FormData.

like image 65
Elias Nicolas Avatar answered Nov 15 '22 12:11

Elias Nicolas