Reputation: 61
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?
Upvotes: 4
Views: 12474
Reputation: 5052
Ready has been replaced by Mounted in Vue.js 2
You should use this:
ready: mounted() {
this.getCounties;
},
Upvotes: 0
Reputation: 94
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
}
Upvotes: 5
Reputation: 17246
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.
Upvotes: 3