Can I append an array to 'formdata' in javascript?
I'm using FormData to upload files. I also want to send an array of other data.
When I send just the image, it works fine. When I append some text to the formdata, it works fine. When I try to attach the 'tags' array below, everything else works fine but no array is sent.
Any known issues with FormData and appending arrays?
Instantiate formData:
formdata = new FormData();
The array I create. Console.log shows everything working fine.
// Get the tags
tags = new Array();
$('.tag-form').each(function(i){
article = $(this).find('input[name="article"]').val();
gender = $(this).find('input[name="gender"]').val();
brand = $(this).find('input[name="brand"]').val();
this_tag = new Array();
this_tag.article = article;
this_tag.gender = gender;
this_tag.brand = brand;
tags.push(this_tag);
console.log('This is tags array: ');
console.log(tags);
});
formdata.append('tags', tags);
console.log('This is formdata: ');
console.log(formdata);
How I send it:
// Send to server
$.ajax({
url: "../../build/ajaxes/upload-photo.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (response) {
console.log(response);
$.fancybox.close();
}
});
How about this?
formdata.append('tags', JSON.stringify(tags));
... and, correspondingly, using json_decode
on server to deparse it. See, the second value of FormData.append can be...
a Blob, File, or a string, if neither, the value is converted to a string
The way I see it, your tags
array contains objects (@Musa is right, btw; making this_tag
an Array, then assigning string properties to it makes no sense; use plain object instead), so native conversion (with toString()
) won't be enough. JSON'ing should get the info through, though.
As a sidenote, I'd rewrite the property assigning block just into this:
tags.push({article: article, gender: gender, brand: brand});
Writing as
var formData = new FormData;
var array = ['1', '2'];
for (var i = 0; i < array.length; i++) {
formData.append('array_php_side[]', array[i]);
}
you can receive just as normal array post/get by php.
use "xxx[]"
as name of the field in formdata (you will get an array of - stringified objects - in you case)
so within your loop
$('.tag-form').each(function(i){
article = $(this).find('input[name="article"]').val();
gender = $(this).find('input[name="gender"]').val();
brand = $(this).find('input[name="brand"]').val();
this_tag = new Array();
this_tag.article = article;
this_tag.gender = gender;
this_tag.brand = brand;
//tags.push(this_tag);
formdata.append('tags[]', this_tag);
...
We can simply do like this.
formData = new FormData;
words = ["apple", "ball", "cat"]
words.forEach((item) => formData.append("words[]", item))
// verify the data
console.log(formData.getAll("words[]"))
//["apple", "ball", "cat"]
On server-side you will get words = ["apple", "ball", "cat"]