Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send XMLHttpRequest with both Header and FormData

I am trying to send a XMLHttpRequest with a header and add a FormData. Is there an (elegant) way i can do something like this:

var formData = new FormData();
formData.append("file", file);
var xhr = new XMLHttpRequest();

xhr.open("POST", "/ajax_gateway.php?mod=fileupload", true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded")
xhr.send(formData, "token=add");
like image 957
LocalHorst Avatar asked Oct 28 '25 12:10

LocalHorst


1 Answers

You cannot specify the Content-Type header when sending FormData because that header automatically gets set to "multipart/form-data" by the browser. You can set other headers though, try this:

var formData = new FormData();
formData.append("file", file);
formData.append("mod", "fileupload");
formData.append("token", "add");

var xhr = new XMLHttpRequest();
xhr.open("POST", "/ajax_gateway.php");
xhr.setRequestHeader("X-Answer", "42");
xhr.send(formData);
like image 131
idbehold Avatar answered Oct 30 '25 10:10

idbehold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!