I have the folowing code:
function checkPermission(user) {
var result = 'default';
$.get('/mymodule/checkPermission.php?user=' + user, function(data) {
result = data; // does not store data into result, why ?
if (result == 'no') {
$('.sorry_msg').show();
}
});
alert(result); // shows "default".
return result == 'yes';
}
Can you explain why this doesn’t work. The problem is that I cannot store the data variable into result, see comments in the code. I guess it is because of the anonymous function, but I don’t know javascript enough to understand exactly what happens.
Also, how can return true or false in checkPermission function based on the result of the ajax call ?
You don’t get the expected result because the ajax callback function is executed asynchronously. This means that the process doesn’t wait for the ajax call to finish. Therefor, before the ajax call has executed the callback function, the outer function
checkPermissionis already terminated and it’s return value will therefor not have been altered by the ajax callback.@pinouchon:
I’ve seen your suggested solution, but I would advise against using synchronous ajax requests, as this will block the whole user interface of the browser for the time it has to wait for the result of the ajax request. I’d suggest you rethink your execution strategy, and build it around asynchronously executed ajax requests.