I’m using ajax to submit a multipart form with array, text fields and files.
I append each VAR to the main data as so
JavaScript
x
12
12
1
var attachments = document.getElementById('files');
2
var data= new FormData();
3
4
for (i=0; i< attachments.files.length; i++){
5
data.append('file', attachments.files[i]);
6
console.log(attachments.files[i]);
7
8
data.append ('headline', headline);
9
data.append ('article', article);
10
data.append ('arr', arr);
11
data.append ('tag', tag);
12
then I use the ajax function to send it to a PHP file to store inside sql DB.
JavaScript
1
10
10
1
$.ajax({
2
type: "post",
3
url: 'php/submittionform.php',
4
cache: false,
5
processData: false,
6
contentType: false,
7
data: data,
8
success: function(request) {$('#box').html(request); }
9
})
10
But on the PHP side, the arr
variable, which is an array appears as a string.
When I don’t send it with ajax as Form data but use the simple $.POST
option I do get it as an array on the PHP side, but then I can’t send the files as well.
any solutions?
Advertisement
Answer
You have several options:
Convert it to a JSON string, then parse it in PHP (recommended)
JS
JavaScript
1
2
1
var json_arr = JSON.stringify(arr);
2
PHP
JavaScript
1
2
1
$arr = json_decode($_POST['arr']);
2
Or use @Curios’s method
Sending an array via FormData
.
Not recommended: Serialize the data with, then deserialize in PHP
JS
JavaScript
1
3
1
// Use <#> or any other delimiter you want
2
var serial_arr = arr.join("<#>");
3
PHP
JavaScript
1
2
1
$arr = explode("<#>", $_POST['arr']);
2