I am trying to upload an image using ajax and FormData
my html looks like:
<form id="profile-photo-form">
<input type="file" id="profile-photo-choose" name="photo_path" accept="image/*">
</form>
and js function called on change of the file selector:
var form_data = new FormData($('#profile-photo-form')[0]);
$.ajax({
type: 'POST',
url: api_url,
data:form_data,
headers:{
'X-CVL-Auth': cookie
},
success: function(result){
but I get a javascript error of:
TypeError: Can only call DOMFormData.append on instances of DOMFormData
this is for a html app loaded on ios (phonegap)
I am trying to upload an image using ajax and FormData
my html looks like:
<form id="profile-photo-form">
<input type="file" id="profile-photo-choose" name="photo_path" accept="image/*">
</form>
and js function called on change of the file selector:
var form_data = new FormData($('#profile-photo-form')[0]);
$.ajax({
type: 'POST',
url: api_url,
data:form_data,
headers:{
'X-CVL-Auth': cookie
},
success: function(result){
but I get a javascript error of:
TypeError: Can only call DOMFormData.append on instances of DOMFormData
this is for a html app loaded on ios (phonegap)
Share Improve this question asked Jan 6, 2015 at 13:51 rpsep2rpsep2 3,12110 gold badges41 silver badges52 bronze badges 2-
Just use
data: $('#profile-photo-form').serialize()
. You do not need to useFormData
asserialize
does all the work for you. – iCollect.it Ltd Commented Jan 6, 2015 at 13:54 -
The error refers to a call to
.append
on a formdata object but your code does not show that. – marekful Commented Jan 6, 2015 at 13:54
1 Answer
Reset to default 8Other ments pointed out that you can just use .serialize()
, however, this won't work on any field that contains an image.
Using this same method, simple add another setting processData: false
to stop the JS from trying to look at your data, and instead just submit everything it gets back as a hash.
I haven't tested every case, but this SHOULD submit the data in the exact same format as if you had submitted without AJAX.
var form_data = new FormData($('#profile-photo-form')[0]);
$.ajax({
type: 'POST',
url: api_url,
data:form_data,
processData: false, // add this here
headers:{
'X-CVL-Auth': cookie
},
success: function(result){