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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With