Hello I have a simple problem. I have two objects in Javascript I am trying to pass together to my server using Axios.
First, a simple object with simple properties and values:
var object1 = {
type: {color: "red", variants: [1,2,4,5]},
content: "xxx"
}
Also a second object which contains File images
let imagesLocalForm = new FormData();
this.imagesLocal.forEach(img => {
imagesLocalForm.append("productPhotos[]", img[0]);
});
Sending either object by themselves will successfully transfer the data to the server. HOWEVER, once I combine the data into an array or another object then all the images from the form object will disappear. ex:
var data = [object1, imagesLocalForm];
or
var data = {info: object1, images: imagesLocalForm};
I use this Axios code to post the data:
Axios.post(this.ADD_MULTI_PRODUCT_API_ENDPOINT, data)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
When i dd() the data array, the response I receive is:
array:2 [
0 => array:2 [
"type" => array:2 [
"color" => "red"
"variants" => array:4 [
0 => 1
1 => 2
2 => 4
3 => 5
]
]
"content" => "xxx"
]
1 => []
]
When i dd() from my php server i receive all of my object1 data but none of the imagesLocalForm data. Could someone explain this behavior to me?
You cannot post JSON data and form data to the same endpoint, it'd simply be impossible because the request body can only have one content type. But you can add you additional data to your existing FormData object.
To do that:
let imagesLocalForm = new FormData();
this.imagesLocal.forEach(img => {
imagesLocalForm.append("productPhotos[]", img[0]);
});
const object1 = {
type: "big",
content: "xxx"
}
for (const key of Object.keys(object1)) {
imagesLocalForm.append(key, object1[key]);
}
Then you can just pass imagesLocalForm to your backend endpoint