Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i return data from this.$http.get in vue js

Hi I'm having problem in returning a data in my ajax call using vue js in laravel 5. I have an array of state and call the function of ajax inside the loop. The problem now is it seems that the ajax cannot returned a value. here's my code:

ready: function() {

    var dData = {};

    for (var i=0; i<this.pState.selectedState.length; i++){
        dData = this.displayCounty(this.pState.selectedState[i])
    }
    console.log(dData);

},
methods:{

    displayCounty: function(val){
        var nData = {};

        // ajax get County list
        this.$http.get('/api/counties/' + val )
            .success(function(counties){
               return counties;
            })
            .error(function(){

            }) //ajaxcall

    }// displaCounty
}

any idea guys?

like image 955
user3814670 Avatar asked Feb 09 '23 06:02

user3814670


2 Answers

If you just want to assign the returned results to a variable then try this:

ready: function() {
    this.getCounties;
},

data: {
    counties: []
},

methods:{

    getCounties: function(val){

        // ajax get County list
        this.$http.get('/api/counties/' + val )
            .success(function(counties){
               this.counties = counties;
            })
            .error(function(){

            }); //ajaxcall

    } // displayCounty
}
like image 118
Jake Ryan Smith Avatar answered Feb 17 '23 20:02

Jake Ryan Smith


I think you are misunderstanding the asynchronous nature of $http.get. The return you have of return counties is not going to effect the return value of displayCounty. displayCounty returns null immediately and the return counties later ends up doing nothing.

A good strategy to use in this case is to have the success callback set counties on the View Model. Then you can setup a watcher on counties and process the data whenever it changes.

like image 28
David K. Hess Avatar answered Feb 17 '23 22:02

David K. Hess