2

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.

1 Answer 1

2
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);
Sign up to request clarification or add additional context in comments.

3 Comments

Ok, I tried this, it works partially, but form_data.append('data_spa':arr); doesn't send the hash at all. The arr variable is a hash, so it captures the values like this: arr['id_sub_category'] = subcategory; Where, in this example, id_sub_category is the column's name, so in PHP i can do something like this: foreach($arr as $key => $val){ // Get columns name with its values $cols[] = "$key='$val'"; } It is done this way to dynamically store data no matter the number of columns, without repeating code.
Ok, I finally solve like this: form_data.append('data_spa', JSON.stringify(arr)); and in PHP $arr = json_decode($_POST['data_spa'],true); And then I got my associative array back, Thank you very much Gian.
try form_data.append('data_spa':arr.serializeArray());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.