send formData using dropzone.js on sendingmultiple
Asked Answered
S

2

5

The dropzone.js documentation/wiki doesn't say how to send form fields.

I just read about the FormData object and it says how to populate the object with the form fields. The problem is that populating the object with the whole form won't get the data send, but if I append the form fields one by one they'll get sent...

This works:

formData.append('name', jQuery('#name').val());

This doesn't:

var myForm = document.querySelector('form');
formData = new FormData(myForm);

The first example will send the #name field but the second won't send anything (just the files).

How can I trigger that? I'd like to make dropzone send the whole form along the files (both in the same request).

init: function() {
    var myDropzone = this,
        submitButton = document.querySelector("[type=submit]");

    submitButton.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        myDropzone.processQueue();
    });

    myDropzone.on('sendingmultiple', function(data, xhr, formData) {
        // this will get sent
        formData.append('name', jQuery('#name').val());
        // this won't
        var myForm = document.querySelector('form');
        formData = new FormData(myForm);
    });
    myDropzone.on('successmultiple', function(files, response) {
        //window.location.replace("/home");
    });
    myDropzone.on('errormultiple', function(files, response) {
        alert(response);
    });
}
Saberio answered 7/5, 2016 at 0:27 Comment(1)
Ok I get it now... you meant manually appending the accepted files on an input inside my form, an input that has nothing to do with dropzone.js, right? I'm not sure how to do this, append the files data to an input.Saberio
F
8

see comments...

myDropzone.on('sendingmultiple', function(data, xhr, formData) {

    // this will get sent
    formData.append('name', jQuery('#name').val());

    // this won't -- we don't need this rn, we can just use jQuery
    // var myForm = document.querySelector('form');

    // you are overwriting your formdata here.. remove this
    //formData = new FormData(myForm);

    // instead, just append the form elements to the existing formData
    $("form").find("input").each(function(){
        formData.append($(this).attr("name"), $(this).val());
    });
});
Fragonard answered 7/5, 2016 at 1:42 Comment(1)
A loop ofc, I'm getting slow... Thanks!Saberio
T
2
init: function() {
  this.on("sending", function(file, xhr, formData) { 

    //formData.append('task_name', jQuery('#task_name').val());

    $("form").find("input").each(function(){
      formData.append($(this).attr("name"), $(this).val());
  });
  
  });

}
Tidy answered 31/7, 2020 at 16:35 Comment(1)
It would be advisable to use the sending function instead of the sendingmultiple function since the user might upload just one file.Tidy

© 2022 - 2024 — McMap. All rights reserved.