Sending XMLHttpRequest with FormData

Marco Bonelli picture Marco Bonelli · Sep 6, 2014 · Viewed 19.8k times · Source

I am trying to make an XHR with JavaScript, but I can't get it to work correctly.

When I see the right requests in the "Network" tab of the Chrome developer tools I see that they have a "Form Data" section where are listed all the informations sent with the request, like this:

formdata

Now, I've tried making my XMLHttpRequest in any way I know, but I can't get that result.

I have tried this:

var xhr = new XMLHttpRequest(),
    form_data = "data%5Btumblelog%5D=drunknight&data%5Bsource%5D=FOLLOW_SOURCE_REBLOG";
    // this is uri encoded: %5b = [ and %5D = ]

xhr.open('POST','https://www.somesite.com/page?' + form_data, false);
xhr.send();

But I got this "Query String Parameters" instead of "Form Data":

querystringparameters

I have also tried this:

var xhr = new XMLHttpRequest(),
    formData = new FormData();

formData.append("data[tumblelog]", "drunknight");
formData.append("data[source]", "FOLLOW_SOURCE_REBLOG");
xhr.open('POST','https://www.somesite.com/page', false);
xhr.send(formData);

But I got this "Request Payload" instead of "Form Data":

payload

And, finally, I have tried this:

var xhr = new XMLHttpRequest(),
    formData = {
        "data[tumblelog]": "drunknight",
        "data[source]": "FOLLOW_SOURCE_REBLOG"
    };

xhr.open('POST','https://www.somesite.com/page', false);
xhr.send(JSON.stringify(formData));

But I got another "Request Payload" instead of "Form Data":

payload2


Now, my question is: how can I send my XMLHttpRequest in order to obtain the same result as shown in the FIRST image?

Answer

Matteo Bernardini picture Matteo Bernardini · Sep 6, 2014

You're missing the Content-Type header to specify that your data is form-like encoded.

This will work:

var xhr = new XMLHttpRequest(),
    data = "data%5Btumblelog%5D=drunknight&data%5Bsource%5D=FOLLOW_SOURCE_REBLOG";

xhr.open('POST','https://www.somesite.com/page', false);

// LINE ADDED
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.send(data);

EDIT

FormData is generally used to send binary data and will automatically set the Content-Type header to multipart/form-data (see FormData Spec and FormData Examples). However you have to make sure the server also accepts request using this MIME-type, which apparently is not your case, as you already tried and it didn't work.