I'm currently refactoring some legacy code which didn't contain much AJAX. Lots of stuff is already finished, but there is one thing I'm currently a bit clueless what to do with it. It's the following function:
function CheckForLogin(){
var loginStatus = <?php if(ISSET($_SESSION["loggedUser"])){
echo 1;
}else{
echo 0;
}?>;
if(loginStatus == 1){
//console.log("CheckForLogin returned ", true)
return true;
}else{
//console.log("CheckForLogin returned ", false)
return false;
}
}
It's used in many places, controlling the flow of the program depending on the loginstatus of the user, like this for example:
if(checkForLogin()){
//doStuff
}else{
//do some other stuff
}
Now, if I make this code asynchronous, how can I make the result of the AJAX call visible to the if? Because once I enter the asynchronous world, the results from there can't really be returned back into the synchronous world (unless I'm using globals or just write the results into some element, database etc.), as far as I understood.
In other words, I'm afraid that all I can return from "checkForLogin()" is a promise object, once I made the server interaction an AJAX.
So, my first question is: Do you think it is a viable solution to just leave the "intermingling" of JS and php as it is right now? Or do you think that the benefits of making this asynchronous and separate php from JS will outweigh the downsides?
And my second question is: If you would advise making this very frequent Check Asynchronous, how can I do it without making the code a hellhole?^^ Using promises inside the normal flow of functions is actually pretty nice, especially compared to using callbacks. But using them inside if-statements? Or is there some way to return the true/false directly depending on the result of the AJAX?