Passing array with objects to PHP via Axios
Get the solution ↓↓↓I am trying to pass an array with objects to PHP via an Axios post. I'm using formData to append or set data.
const product_id_list = [{ title: 'hello' }, { title: 'ohhello' }]
const bodyFormData = new FormData();
bodyFormData.append('post_id', post_id)
bodyFormData.append('action', 'uploadShowcaseContent')
product_id_list.forEach((item) => {
bodyFormData.append('product_id_list[]',item);
});
axios.post(`${__WP_VARS.AJAX_URL}`, bodyFormData)
.then((resp) => {
console.log('post respect is', resp)
})
Then in my PHP, I am trying to loop through the array and get the title string.
$content = $_POST['product_id_list'];
The $content variable does tell me I have an Array. However, when I do a foreach on the Array
foreach ($content as $item) {
echo $item;
}
In my console response I get data: "[object Object][object Object]"
When I try to echo out the title,
foreach ($content as $item) {
echo $item->title;
}
I get an empty string.
I am stuck on trying to figure out how to loop in PHP and get the object key, value when passing it via AXIOS.
Answer
Solution:
Here you are passing a string, many times, changing the value:
bodyFormData.append('product_id_list[]',item);
so you are actually sending a string instead of an array. You should instead just stringify your arrays and objects before sending them:
const product_id_list = [{ title: 'hello' }, { title: 'ohhello' }]
const bodyFormData = new FormData();
bodyFormData.append('post_id', post_id)
bodyFormData.append('action', 'uploadShowcaseContent')
bodyFormData.append('product_id_list',JSON.stringify(product_id_list));
...
then to see what you are actually receiving in php:
$content = $_POST['product_id_list'];
var_dump($content)
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: videoxxx
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.