6

I am working on a project with vue.js and to handle my AJAX requests I use Axios, I wonder if it is possible to pass as a parameter to a POST request an array of objects, of this type:

[{id: 1, name: 'max'}, {id: 2, name: 'jhon'}, {id: 3, name: 'anna'}]

If possible, what is the best way to do this?

FeRcHo
  • 1,119
  • 5
  • 14
  • 27

3 Answers3

8

Sure!

let arrOfObj = [
  { name: 'John', lastName: 'Doe' },
  { name: 'Jane', lastName: 'Doe' }
]

axios.post('url_here',arrOfObj)
.then(console.log)
.catch(console.log)
Roland
  • 24,554
  • 4
  • 99
  • 97
5

Yes, it's very possible

let data = [
    {id: 1, name: 'max'}, 
    {id: 2, name: 'jhon'}, 
    {id: 3, name: 'anna'}
];

let formdata = new FormData();
formdata.append('data',JSON.stringify(data));

axios.post('/url`',formdata)
.then(res => console.log(res))
.catch(err => console.log(err)

On the receiving end (assuming it's PHP & Laravel)

$data = json_decode($request->data);

then loop through $data as it's a normal array

Lema
  • 69
  • 1
  • 5
1

Lema's answer was the only one that worked for me while using axios + vue + .net Core.

I was trying to send a post to my backend which was expecting an array. Following Lema's implementation I received an string and then deserialized the json string to the type I was expecting.

    public IActionResult PostMethod([FromForm]string serialized_object_name){
         var expectedArray = JsonConvert.DeserializeObject<ArrayTypeNeeded[]>(serialized_object_name);
    }
Fernando Wolff
  • 216
  • 3
  • 6