Passing array with objects to PHP via Axios ← (PHP)

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)

Source