Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload file and JSON data in the same POST request using jquery ajax?

I am trying to send a POST request using jQuery Ajax, where I would like to upload a file and some json data. Please find code,

var logoImg = $('input[name="logoImg"]').get(0).files[0];
var formData = new FormData();
formData.append('logo', logoImg);

var objArr = [];
objArr.push({
  "id": id,
  "name": userName
});

var obj = [{
  "objArr": objArr,
  "formData": formData
}];

$.ajax({
  type: "POST",
  url: url,
  dataType: "json",
  data: JSON.stringify(obj),
  contentType: "application/json",
  cache: false,
  async: false,
  complete: function(data) {
    alert("success");
  }
});

But I am getting Internal server error: 500 and the backend API is not called.

Please help me to send a file and an array obj in same AJAX request. Thanks in advance

like image 557
surendarmx Avatar asked Aug 09 '17 15:08

surendarmx


1 Answers

You cannot serialise any binary data you send in the request.

To send additional information with the FormData object, just use the append() method to add it, similar to how you are with the image itself:

var logoImg = $('input[name="logoImg"]').get(0).files[0];
var formData = new FormData();
formData.append('logo', logoImg);
formData.append('id', id);
formData.append('name', userName);

$.ajax({
  type: "POST",
  url: url,
  data: formData,
  contentType: false,
  processData: false,
  cache: false,
  complete: function(data) {
    alert("success");
  }
});

Note the important parts in the options are setting contentType and processData to false, and removing async: false so that the request occurs asynchronously.

Finally, note that if the inputs you want to send in the request are all contained within the same form you can use the FormData constructor to simplify your code to just:

var formData = new FormData($('#yourForm')[0]);
like image 56
Rory McCrossan Avatar answered Oct 21 '22 06:10

Rory McCrossan