1

I have this 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 then I get at least line console.log(aaa) - > undefined...

Why? First console.log work ok but outside ajax I cant get db_data... WHy?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
MonkeyBusiness
  • 583
  • 1
  • 8
  • 23
  • You are ordering a pizza, then trying to eat it before it is delivered! Ajax is an async call and the `success` gets called-back long after the last `console.log` executes. – iCollect.it Ltd Feb 05 '16 at 14:22
  • Only use the data *inside* the callback (or use promises). The question is "what do you want to do with the data next?" – iCollect.it Ltd Feb 05 '16 at 14:24
  • @David: Depends on what he wants to do with it next. That dupe is not quite the same code as shown here. – iCollect.it Ltd Feb 05 '16 at 14:29
  • @GoneCodingGoodbye: How does it make a difference? The code may not be exactly identical, but the concept is still the same and explained pretty canonically in the linked question. The OP simply needs to understand the concept of what "asynchronous" means. The rest is minutia. – David Feb 05 '16 at 14:33
  • @David: I was trying to find out what they *actually wanted*, as the example was insufficient to determine the real problem, but that is a moot point now it is closed. – iCollect.it Ltd Feb 05 '16 at 14:34
  • @MonkeyBusiness change async: false then try then sure, you get it result outside ajax – GuRu Feb 05 '16 at 14:38
  • @MonkeyBusiness: Ignore anyone that every suggests `async: false` as a solution to any problem. `async: false` is a shiny door leading to a *very* bad place (and is being removed from jQuery). Work *with* the async model provide by browsers and don't try to avoid it. – iCollect.it Ltd Feb 05 '16 at 15:38

1 Answers1

2

You are ordering a pizza, then trying to eat it before it is delivered! Ajax is an async call and the success gets called-back long after the last console.log executes.

You need to only use Async data in side the callbacks.

An alternative is to use the promise returned by Ajax so you code becomes a function that "promises to return the data":

// Return the Ajax promise
function aaa() {
  return $.ajax({
    url: "http://localhost:8888/aaa/{{$article->id}}",
    type: "GET",
    async: true,
    dataType: "json",
  });
}

// and use like this

aaa().then(function(data){ 
   // Do something with the data
}).fail(function(data){ 
   // Do something with the data when it fails
});

Promises make the functions reusable.

iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202