How to submit Dropzone on button?

single-image

Ever wonder how to send a form using Dropzone? If so, be sure to read this article. You will learn from it how to achieve it while adding additional fields to the form.

Sometimes we don’t want photos added from Dropzone to be sent automatically. Most often this happens when our form contains additional fields and we want to give them to users before submitting.

Dropzone is a great tool that is easy to configure, but what we want to achieve requires a small hack.

The whole way is that we block sending the form after adding photos in accordance with the documentation, then we add the button and send the form after adding it.

Additionally

It is also worth noting that we will add additional fields besides the drop drop to the form in the form of a JavaScript object – FormData

1. Block auto queue

According to the documentation, we need to add autoProcessQueue: false to the configuration of our dropzone element

var libraryDropzone = new Dropzone('#library_form ', {
    autoProcessQueue: false,
})

2. Create an event by clicking the button

Of course, we assume that the button can be anywhere on the page. In my example, the button got id library_form_submit

$('#library_form_submit').click(() => {
    libraryDropzone.processQueue()
})

3. Adding additional fields when submitting the form

If we want to send any additional fields in the form, we can do it with a custom event made available by Dropzone’s library.

It is worth noting that there is an object of FormData type so we can also send e.g. other files.

libraryDropzone.on('sending', function (file, xhr, formData) {
    formData.append('fileable_id', $('#fileable_id').val())
    formData.append('campaign_step_id', $('#campaign_step_id').val())
})

Result Code

After putting everything together, it should look like this:

var libraryDropzone = new Dropzone('#library_form ', {
    autoProcessQueue: false,
})

libraryDropzone.on('sending', function (file, xhr, formData) {
    formData.append('fileable_id', $('#fileable_id').val())
    formData.append('campaign_step_id', $('#campaign_step_id').val())
})

$('#library_form_submit').click(() => {
    libraryDropzone.processQueue()
})

Please leave me comment if you have any question. If you liked this post, go to my instagram and follow me to stay up to date!

You may like