24

I am trying to submit a file from a form using jQuery's ajax method:

var ofile=document.getElementById('image').files[0];
var formdata = new FormData();
formdata.append("image",ofile);

$.ajax({
    url:'elements/save_elements',
    data:formdata,
    type:'POST'
});

This results in the error TypeError: 'append' called on an object that does not implement interface FormData.

What causes this error? It doesn't happen on the actual formdata.append, but inside jQuery.

Niels Abildgaard
  • 2,662
  • 3
  • 24
  • 32
user2889070
  • 275
  • 1
  • 2
  • 6

3 Answers3

112

I was having the same problem with similar code. There's a severe dearth of information about this error, so since the OP didn't elaborate:

With some debugging I realised the error was being thrown by the ajax call in the depths of jquery, not the actual append. Turns out I'd forgotten to add processData: false, contentType: false to the ajax request; Doing so fixed the problem.

Bhau
  • 1,121
  • 1
  • 6
  • 2
  • Thank you. I read about processData:false... but not contentType – deach Mar 19 '14 at 07:20
  • 1
    Turns out if you misspell ``processData`` as ``proccessData`` you will also get the same error. Reasonable. – iiminov Dec 12 '14 at 11:45
  • i am so glad this was the first thing that showed up when i searched google for the error mesaage. – w-- Dec 21 '14 at 03:00
  • @w-- Lucky you! With me it was the 50+ thing I read. Because I -- after 15 years of coding -- did not google the error message right away but instead googled all kinds of ill-phrased wishes … – maxpower9000 Aug 28 '15 at 12:17
  • But.. I need to use multipart/form-data as my content-type.. because that's what my REST api is looking for... maybe I can just... assume incoming requests are of type multipart/form-data? – CaffeinateOften Sep 08 '16 at 18:50
8

It works fine when you add the the following to the ajax object:

contentType: false,
processData: false,

So it should look like:

$.ajax({
    url:'elements/save_elements',
    data:formdata,
    type:'POST',
    contentType: false,
    processData: false,
});
Kelderic
  • 6,502
  • 8
  • 46
  • 85
Canaan Etai
  • 3,455
  • 2
  • 21
  • 17
2

Adding these parameter to ajax solve the problem

$.ajax({
      url: 'upload_ajax.php',
       type: 'POST',
       data: formData,
       contentType: false,
       processData: false,