javascript - How to define variable before ajax call -


this question has answer here:

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

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -