javascript - How to define variable before ajax call -
this question has answer here:
- how return response asynchronous call? 21 answers
i have code:
function aaa (){ var db_data; $.ajax({ url: "http://localhost:8888/aaa/{{$article->id}}", type: "get", async: true, datatype: "json", success: function(data) { db_data = data; console.log(db_data); }, error: function (data) { console.log(data); console.log('greska neka'); } }); console.log(db_data); };
but @ least line console.log(aaa)
- > undefined...
why? first console.log work ok outside ajax cant db_data... why?
you ordering pizza, trying eat before delivered! ajax async call , success
gets called-back long after last console.log
executes.
you need only use async data in side callbacks.
an alternative use promise
returned ajax code becomes function "promises return data":
// return ajax promise function aaa() { return $.ajax({ url: "http://localhost:8888/aaa/{{$article->id}}", type: "get", async: true, datatype: "json", }); } // , use aaa().then(function(data){ // data }).fail(function(data){ // data when fails });
promises make functions reusable.
Comments
Post a Comment