My function fetches if the user is banned and i want to return a variable that determines if a popup displays; but as I’ve found out you can’t return a variable from a getJSON function.
function fetchban() {
$.getJSON('/fetchban.php',function(data) {
if(data==0) {
var banned = data;
} else {
$.each(data,function(index,result) {
$('#ban-prompt').html(result);
$('.popup-background').show();
$('#ban-container-2').show();
});
}
});
return banned;
}
$('.button').click(function() {
var banned = fetchban();
if(banned==0) {
//display-popup
}
});
There are alot of lines i call the fetchban function, so i would prefer the getJSON in a function. What is the solution?
There are two problems with your function.
The first, and the most significant, is that it assumes that
getJSONis synchronous. It is asynchronous by default, meaning it’s impossible forfetchbanto return a value based on the data retrieved. Instead,fetchbanshould accept a callback it calls with the result.The second (which will go away anyway once you fix the first), is that you’re trying to return a variable from
fetchbanthat isn’t declared (because you declare it inside yourgetJSONsuccess handler).So you’d change
fetchbanto look something like:And then instead of:
do this:
…or much better, fetch it earlier so you already have that information when the
clickarrives. Users don’t like delays when they click, and even the best case on a web round-trip is noticeable to human beings.