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
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.
Just use the . success() callback method and pass 'data' to a function and call alert there.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With