0

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
  • Use the serialize() function of jQuery instead of FormData Commented Apr 8, 2020 at 20:07
  • Are you sure your backend can't handle multipart/form-data? Try adding contentType: false. Commented Apr 8, 2020 at 20:09

2 Answers 2

1

u should also add contentType: false

  $.ajax({
        url: "http://localhost:8080/example",
        type: "post",
        data: data,
        processData: false,
        contentType: false,
        success: function (data) {

         }
    });
Sign up to request clarification or add additional context in comments.

1 Comment

Why should you add this? Can you explain your contribution?
0

FormData is always sent as multipart/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.

const data = {foo: "bar"};

Also, don't use processData: false when you're doing this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.