iuliu.net
iuliu.net

Reputation: 7135

Send FormData object AND an additional parameter via ajax

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.

Upvotes: 26

Views: 44530

Answers (2)

Borik Bobrujskov
Borik Bobrujskov

Reputation: 845

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

Upvotes: 39

Jiri Tousek
Jiri Tousek

Reputation: 12440

You need to either add it directly to formData (just as you did with 'file'), or alternatively use query (GET) parameters.

Upvotes: 2

Related Questions