Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
162
rated 0 times [  166] [ 4]  / answers: 1 / hits: 32897  / 10 Years ago, sat, september 6, 2014, 12:00:00

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?


More From » ajax

 Answers
7

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.


[#69552] Wednesday, September 3, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
billier

Total Points: 153
Total Questions: 85
Total Answers: 91

Location: Monaco
Member since Sun, Jan 16, 2022
2 Years ago
billier questions
Sun, Dec 27, 20, 00:00, 4 Years ago
Tue, May 26, 20, 00:00, 4 Years ago
Fri, Apr 3, 20, 00:00, 4 Years ago
;