How to post array of object to PHP using axios?

Viewed 584

let dataArray = [
  {
    fname: 'name #1',
    choice: 'choice #1',
  },
  {
    fname: 'name #2',
    choice: 'choice #2',
  },
  // more data could be appended here
];

I have a data structure as above in my VueJS form. How do I go about sending this data to my PHP back-end and save it into the database?

My attempts so far were useless. I'm using axios to post my data to my PHP back-end. I have tried using FormData() and JSON.stringify and various ways of getting the data on the PHP side.

To my understanding, axios takes care of the json formatting internally.

This is my data structure in the app:

data: {
  enteredDataArray: [{
    fname: '',
    radioVal: ''
  }]
}

onSubmit(evt){
  evt.preventDefault();
  axios.post('api.php', app.enteredDataArray)
  .then(res => console.log(res))
  .catch(err => console.log(err))
}

$data = $_POST;
1 Answers

PHP $_POST expect a FormData.

If you want to receive a JSON in PHP, $_POST is not the way, you can handle doing this:

$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
var_dump($input)
Related