Search code examples
vue.jsaxiossymfony4

Access vue js data with axios post form symfony


Hi I'm trying to access vue.js data array from symfony back-end via axios. This is my code.

var vm = new Vue({
                el: '#el',
                delimiters: ["[[", "]]"],
                data: {
                    brand: 0,
                    model: 0,
                    country: "europe",
                },
                created: function () {
                },
                updated: function () {
                    axios.post('http://localhost:81/lnt/public/member/car_result', {data: this.data})
                            .then(function (response) {

                            });
                }
            });

This is my symfony code,

/**
 * @Route("/car_result", name="car_result", methods="POST")
 */
public function carResult(Request $request) {
    $data = $request->getContent();
    $data = json_decode($data, true);

    $brand = $data['brand'];
    .......
}

But unfortunately what I'm getting is there is no index called brand :(. It would be great if someone can help me on this. Think I need to find a way to send complete data array to backend I can send data like this,

axios.post('http://localhost:81/lnt/public/member/car_result', {brand: this.brand})

Solution

  • There are two problems with this code.

    1 this.data is not defined

    Your data is the following:

    {data: this.data}
    

    And you probably hope to have structure

    {
        data: {
            brand: 0,
            model: 0,
            country: "europe",
        }
    }
    

    But is does not work because of this.data is not data property of Vue instance. It can seems to be so magical, but calling this['property'] you asking Vue to value of reactive property of data, so if you want to get brand you should type this.brand.

    2 your models of data are different on client and server

    Event if this structure of json would be achieved then in Symfony's controller you asking about

    $brand = json_decode($request->getContent(), true)['brand'];
    

    but actually, your request does not have 'brand' key on the first level. You should replace your backend code by

    $brand = json_decode($request->getContent(), true)['data']['brand'];
    

    or replace your client code code pasting body of request as

    {brand: this.brand}