Gabriel Alejandro
Gabriel Alejandro

Reputation: 225

Ajax & php: FormData object

I'm trying to send some data to PHP via jQuery AJAX. It only works if I 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}

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.

Upvotes: 2

Views: 1246

Answers (1)

Gian Tomakin
Gian Tomakin

Reputation: 193

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

Upvotes: 2

Related Questions