Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submitting a file with jQuery.ajax gives TypeError

Tags:

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.

like image 302
user2889070 Avatar asked Nov 01 '13 08:11

user2889070


Video Answer


2 Answers

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.

like image 62
Bhau Avatar answered Oct 01 '22 20:10

Bhau


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, }); 
like image 44
Canaan Etai Avatar answered Oct 01 '22 19:10

Canaan Etai