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?
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With