17

I'm trying to get the result of an ajax request to set in a variable which I can access outside that request. I've tried this JQuery - Storing ajax response into global variable but my variable beer remains undefined outside the $.getJSON and $.ajax functions (I tried both).

Here is my code and where I am able to see the results from the console.log(beer).

var beer;
$.getJSON(jsonUrl, function (json) {
    beer = json;
    console.log(beer); // returns beer
});
console.log(beer); // returns undefined

var beer = (function () {
    var result;

    $.ajax({
        url: jsonUrl,
        success: function (data) {
            result = data;
            console.log(beer); // returns beer

        }
    });
    console.log(result); // returns undefined
    if (result) return result;
})();
console.log(beer); // returns undefined
Moshe
  • 4,635
  • 6
  • 32
  • 57
Sebastien
  • 2,607
  • 9
  • 30
  • 40

3 Answers3

21

That's an asynchronous request, so it gets fired off, but your script doesn't wait around for a response before it moves on. If you need to wait on a ajax request to finish, try something like this:

var beer;
$.getJSON(jsonUrl,function(json){
    beer = json;   
    checkDrink();                
});         

function checkDrink() {
    console.log(beer);
}   
chprpipr
  • 2,039
  • 16
  • 17
  • 1
    So how can I access beer later in the script from outside the function? – Sebastien Jan 21 '11 at 21:32
  • 1
    Anything that depends on the result of that JSON request needs to be in that separate function. – chprpipr Jan 21 '11 at 21:36
  • And why wouldn't this work ? beer = $.ajax({ url: jsonUrl, success: function(data) { return data; } }); – Sebastien Jan 22 '11 at 00:55
  • 1
    "success" is an event on the $.ajax() object. It doesn't execute that function until it gets a response from the server, which could be 10ms or 10 minutes from the time its executed. Meanwhile, your main code line keeps executing. – chprpipr Jan 22 '11 at 01:20
10

Suggest the code below:

var beer = $.ajax({
    url: jsonUrl,
    async: false,
    dataType: 'json'
}).responseJSON;

The key moments are:

  1. set async to false, to return result as variable, not call success callback asynchronious
  2. set dataType to json to parse server response string as json
userlond
  • 3,632
  • 2
  • 36
  • 53
1

The problem is that you're trying to access the data before it actually comes back from the server, the 'success' function is actually a callback that gets called when the ajax call finishes successfully. The $.ajax (or $.get) functions return inmediatly...

You would need to somehow signal to the interested functions that you got the data into the 'beer' var inside your success callback

Jaime
  • 6,736
  • 1
  • 26
  • 42