Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery - Store Ajax jSON response as variable

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
like image 972
Sebastien Avatar asked Jan 21 '11 21:01

Sebastien


People also ask

How do I save Ajax response to global variable for reuse?

Solution 1 var myResponse; $. ajax({ url: 'PageMethod/GetData', method: 'post', dataType: 'json', data: JSON. stringify({ dataId: "xxx" }), contentType: 'application/json', success: function (data) { myResponse = data.

How do I pass an outside variable to an Ajax success function?

Just use the . success() callback method and pass 'data' to a function and call alert there.


1 Answers

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);
}   
like image 132
chprpipr Avatar answered Oct 19 '22 21:10

chprpipr