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)
The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the fetch() or XMLHttpRequest.
append() The append() method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.
Form data is information provided by the user through interaction with an element in a HTML form, such as a text input box, button, or check box. The information is transmitted as a series of name and value pairs.
There is no way to retrieve the files after you've appended them in to a formData-object I believe. You'll have to send the formData-object somewhere and then get the files from a req-object or something like that.
Other comments 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){
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With