skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. u should also add contentType: false

      $.ajax({
            url: "http://localhost:8080/example",
            type: "post",
            data: data,
            processData: false,
            contentType: false,
            success: function (data) {
    
             }
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search