Ajax is such a pain, in that the benefits of asynchronocity also has it's drawback (at least until we think of it as the norm).
You need to return the result in the callback, not just set the variable, which, as you discovered, has no value since the ajax is still being tended to. Here's one example of how to change your code easily:
function freelog(login) {
var data = {login:login};
$.post ('freelog.php', data, function(response){
if(response == '1') {
freelogin = true;
} else if(response == '0') {
freelogin = false;
} else {
freelogin = response;
}
return freelogin;
});
}
All I did was move the return to within the post callback, so it won't get returned until the request is done. As advised by others, it is better to get more sophisticated and have things like:
A spinner or "checking" or some kind of feedback, assuming the request takes longer than a millisecond.
Having the freelogin
actually return something meaningful. Assuming it's being called by another function that is awaiting the response to output "Not available" you should be fine, but if you are just outputting the freelogin
or have some code that depends right away on the response, you'll need to further revamp to get your script asynchronous.
Last bit of advice, here's a nice way to tighten up that callback function:
$.post ('freelog.php', data, function(response){
return (Number(response) <= 1) ? Boolean(Number(response)) : response;
});