Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send FormData object AND an additional parameter via ajax

Tags:

I have managed to send a FormData object like so:

var formData = new FormData(); formData.append('file', this.files[0]); $.ajax({    url: urlUploadProductsFile,    type: 'POST',    data: formData,    cache: false,    contentType: false,    processData: false }, 'json'); 

Now what I want to do is add an additional CustomerId to send to the server. The following won't work:

var formData = new FormData(); formData.append('file', this.files[0]); $.ajax({    url: urlUploadProductsFile,    type: 'POST',    data: { "file": formData, "CustomerId": 2 },    cache: false,    contentType: false,    processData: false }, 'json'); 

And I also tried the following variations:

data: { "file": formData, "CustomerId": 2 }, processData: true

data: JSON.stringify({ "file": formData, "CustomerId": 2 })

data: { "file": JSON.stringify(formData), "CustomerId": 2 }

data: { file: formData, CustomerId: 2 }

Any help appreciated.

like image 932
iuliu.net Avatar asked Apr 06 '16 10:04

iuliu.net


People also ask

Can we send object in formData?

Yes you can, you can append to formData objects.

How can add multiple form data using jquery Ajax?

For Sending or inserting or saving multiple data in single click then you have to use Jquery and javascript code. By using Jquery or Javascript code you can generate dynamic HTML field in your HTML form. We can generate any dynamic HTML field by using Jquery and append into your form fields.

What is formData in Ajax?

The jQuery Ajax formData is a method to provide form values like text, number, images, and files and upload on the URL sever. The jQuery Ajax formData is a function to create a new object and send multiple files using this object.


1 Answers

Try:

var formData = new FormData(); formData.append('file', this.files[0]); formData.append('CustomerId', 2);  /*  note:: appending in form Data will give "csrf token mismatch error".   so better you make a input feild of type hidden with name = CustomerId   and value =  2  */   $.ajax({    url: urlUploadProductsFile,    type: 'POST',    data: formData,    cache: false,    contentType: false,    processData: false }, 'json'); 
like image 75
Borik Bobrujskov Avatar answered Oct 12 '22 01:10

Borik Bobrujskov