Utilize dropzone.js to transmit formData when sending multiple files simultaneously

I've been exploring the dropzone.js documentation/wiki and I noticed that there is no clear explanation on how to send form fields along with files.

Recently, I came across the FormData object which provides a way to populate form fields within an object. However, I encountered an issue where simply populating the whole form object doesn't result in the data being sent. But, appending the form fields one by one seems to work...

For example:

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

But this approach doesn't work:

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

In the first example, only the #name field gets sent, whereas in the second example nothing gets sent except the files.

Is there a way to trigger the sending of form fields along with the files in a single request using dropzone? That's my main goal.

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);
    });
}

Answer №1

check out the comments...

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

    // include this data in the form submission
    formData.append('name', jQuery('#name').val());

    // we don't need this right now, we can use jQuery directly
    // var myForm = document.querySelector('form');

    // you're replacing the formdata here.. don't need this
    //formData = new FormData(myForm);

    // instead, add the form elements to the existing formData
    $("form").find("input").each(function(){
        formData.append($(this).attr("name"), $(this).val());
    });
});

Answer №2

initialize: 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());
  });
  
  });

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The resolution of Angular 8 resolver remains unresolved

I tried using console.log in both the constructor and ngOnInit() of Resolver but for some reason, they are not being logged. resolve:{serverResolver:ServerResolverDynamicDataService}}, console.log("ServerResolverDynamicDataService constructor"); console ...

What is the best way to ensure a consistent time interval between invoking two functions in JavaScript?

Is there a way to create a code that will call one function, let's say toStart(), and then immediately call another function, toStop(), exactly two seconds after the first function is initiated? I want this process to continue until a specific button, ...

Transferring PHP objects to JavaScript arrays

I have been searching for a unique JS array of PHP arrays with a specific format. After hours of research and attempts to use the json_encode PHP function, I still haven't achieved the desired format. Here's an example of what I'm looking fo ...

Struggling to implement sparklines for real-time data in the AngularJS adaptation of the SmartAdmin template

Currently, I am embarking on a project that involves utilizing the AngularJS version of the SmartAdmin Bootstrap template foundhere. Within this project scope, I am required to integrate sparklines into various pages. I have successfully implemented them ...

Changing HTML elements dynamically within an ng-repeat using AngularJS directives

I have devised an angular directive where I execute an ng-repeat. The fundamental purpose of this directive is to interchange itself with a distinct directive that depends on a value forwarded into the original directive: <content-type-directive type=" ...

Disable form input fields while keeping all other elements enabled

Currently, I am facing a dilemma where I must deactivate specific input fields within a form. Given that there are numerous fields to consider, individually disabling each one seems impractical. Can anyone offer advice on how to disable a set of elements ...

How can we reduce the size of a JSON object in Typescript before sending it to the client?

Currently, I am faced with a common challenge. I have a database object that is a standard JS object originating from a document database, and my goal is to transmit this object to the client. However, certain fields contain sensitive information that shou ...

Adjust the color scheme of the menu to match the newly updated background image

On the homepage, there is a background slideshow playing. The issue arises when the menu becomes invisible against a dark background due to its dark font color. It would be ideal for the menu's color to dynamically change with the background. I' ...

What could be the reason that angularjs html template requests aren't appearing in the top websites when viewed in a

After referring to the link , I discovered a way to determine which programming tools different sites use for application development. However, when I debug HTTP requests using Firebug, I noticed that HTML requests are not explicitly shown in the log. Alt ...

Clicking within the text activates the dropdown menu, but clicking outside the text does not

My custom drop down menu is not functioning properly. When I click on the text, it successfully links to another place, but when I click beside the text, it does not link. Can you please help me identify what's wrong here? Your assistance would be gre ...

I am having trouble getting text to display properly in a jQuery Mobile dialog

I am attempting to dynamically set the header and button texts using JavaScript, but unfortunately it's not working as expected. To demonstrate the issue, I have added my code on jsfiddle: http://jsfiddle.net/tMKD3/8/. Here is the HTML code: <bod ...

What is the best way to include generic HTML content in an Angular 2 component?

I am looking to design a versatile modal component that can accommodate various elements, ranging from text to images and buttons. If I were to implement something like the following: <div class="Modal"> <div class="header"></div> ...

There seems to be a problem with the sorting functionality on the table in React JS,

My React table is functioning well with all columns except for the country name column. I double-checked the API and everything seems to be in order, but I'm stuck on how to troubleshoot this issue. const Table = () => { const[country, setCount ...

Creating new rows in PHP form using different ID and name pairs

I am seeking a solution to dynamically add rows of inputs using a button. I have come across several examples, but most of them change the name attribute of the HTML elements (e.g. name = 'price1', name = 'price2'), causing issues with ...

Making Life Easier with Netsuite: Streamlining Deposit Generation

Recently, I developed a Suitelet to streamline the process of applying deposits for Cash Sales. The idea was for users to upload a CSV file containing Cash sales records, which the script would automatically use to apply the deposits and create deposit r ...

programming issue: unable to resolve

The issue at hand involves creating a function that can determine the presence of all the letters from the second element in the array within the first element. For example, when given the arguments ["hello", "hey"], the function should return false becaus ...

Tips for crafting services using $q and $http requests while avoiding redundancy

Is there an elegant way to write AngularJS services without repetitive $q syntax? I currently write services like this: (function() { function ServiceFactory($q, $timeout, $http) { return { getFoo: function() { va ...

Tips for customizing a single row in v-data-table? [Vuetify]

My goal is to change the background color of a specific row that contains an entry matching the value of lowestEntry. <v-col cols="8"> <v-data-table :loading="loadEntryTable" loading-text="Searching for data..." ...

Mastering the Art of Nodemailer

Can anyone advise on how to utilize nodemailer with dynamic email and password retrieved from a database? export const mailTransporter = nodemailer.createTransport({ service: 'gmail', auth: { user: email_user, pass: email_pass, }, } ...