Gabriel Alejandro Gabriel Alejandro - 5 months ago 13
Ajax Question

Ajax & php: FormData object

I'm trying to send some data to PHP via Jquery ajax, it works if I only send the data like this:

type: 'POST',
dataType: 'json',
//processData: false,
//contentType: false,
url: 'productEdit.php',
data: {'data_spa':arr, 'id': id, 'table': table_name, 'insert': values}


Here, it receives the values as expected, but whenever I try to send a FormData() object it stops working. However if I send just the form_data (uncommenting processData and contentType) it works:

type: 'POST',
dataType: 'json',
processData: false,
contentType: false,
url: 'productEdit.php',
data: form_data


All I'm trying to do is send the values and the form_data as json, like this:

data: (form_data, {'data_spa':arr, 'id': id, 'table': table_name, 'insert': values})


And in PHP it should receive the data like this:

$arr = $_POST['data_spa'];
$image_file = $_FILES['file']['name']


By the way, I'm creating the FormData object like this:

var file_data = $('#imageProduct').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);


I hope you can help me solve this issue.

Answer
var file_data = $('#imageProduct').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('data_spa':arr);
form_data.append('id': id);
form_data.append('table': table_name);
form_data.append('insert': values);