Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is FormData erroring

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)

like image 983
rpsep2 Avatar asked Jan 06 '15 13:01

rpsep2


People also ask

What is the purpose of FormData?

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.

What is the use of FormData append?

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.

What is FormData in a request?

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.

How do I extract files from FormData?

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.


1 Answers

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){
like image 149
Rockster160 Avatar answered Oct 12 '22 23:10

Rockster160