I am trying execute this simple AJAX request with JQuery:
const data = new FormData();
data.append("foo", "bar");
$.ajax({
url: "http://localhost:8080/example",
type: "post",
data: data,
processData: false
});
I check request by Google Chrome developer tools. I see that Content-type is application/x-www-form-urlencoded; charset=UTF-8
which is expected, but actual data sent in multipart encoding:
------WebKitFormBoundaryEzaaFpNlUo3QpKe1
Content-Disposition: form-data; name: "foo"
bar
------WebKitFormBoundaryEzaaFpNlUo3QpKe1--
Of course my backend application doesn’t expect such encoding and fails. What is wrong and how to force JQuery to send data in urlencoded format? I tried pass extra headers or contentType options, but nothing works.
2
Answers
FormData
is always sent asmultipart/form-data
. It’s usually used when you’re uploading a file or blob, which can’t be URL-encoded.If you want URL-encoded, don’t use
FormData
. Use a regular object, and jQuery will encode it properly.Also, don’t use
processData: false
when you’re doing this.u should also add
contentType: false