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?

2
  • Possible duplicate of javascript - pass object via post Commented Apr 11, 2018 at 17:27
  • Why wouldn't it be possible? Commented Apr 11, 2018 at 17:30

3 Answers 3

9

Sure!

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

axios.post('url_here',arrOfObj)
.then(console.log)
.catch(console.log)
Sign up to request clarification or add additional context in comments.

Comments

6

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

Comments

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);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.