Sartheris Stormhammer
Sartheris Stormhammer

Reputation: 2564

Error when trying to send FormData with jQuery.ajax

I have a file which I want to send to the server. The file is being passed within a FormData object and not as a path URI. This is the code I am using:

let formData = new FormData();
formData.append('enctype', 'multipart/form-data');
formData.append('mode', 'fileInsert');
formData.append('conId', 'asdasd5535asf');
formData.append('user', 'user2422424');
formData.append('filesNumber', 1);
formData.append('msgType', 'fil');
formData.append('file0', file);

$.ajax({
    data: formData,
    success: function (a, s) {
        debugger;
    }
});

When the code reaches the $.ajax call it throws this error:

Uncaught TypeError: Illegal invocation

What is wrong? Note that the jQuery AJAX is being configured earlier, with post type, URL and such.

Upvotes: 2

Views: 3281

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You need to set the following properties on your AJAX request:

contentType: false, 
processData: false

Setting contentType to false stops the content-type header being set. Similarly, setting processData to false will stop the content of the request being encoded, which is needed when sending a FormData object.

For more information on these and other $.ajax properties, see the jQuery Documentation

Upvotes: 4

Related Questions