I have a javascript function where I require it to verify some information from a database before proceeding. This is a simple boolean condition. If true, proceed, else terminate. The problem seems to be that the javascript function is immediately evaluating the function call as 'false', thereby terminating execution. It does this before the function actually returns, so even if the internal function returns true, the main function terminates incorrectly.
I'm still pretty new to js, php, and ajax. I'm guessing that this is a result of an asynchronous php call. Am I right about this conclusion? If so, is there a way to make the javascript function pause until it receives the results of the function call?
Here is my code. Thanks for any advice.
First, the main javascript function that gets called with the button onclick (in file 'users.php'):
function deleteUser() {
//check for excessive inactivity
if (verifySession()) {
console.log("verified");
} else {
console.log("verification failed"); //<--line 33
return false;
}
//continue on...
This is the function called by the if statement (in file 'session_handler.js'):
function verifySession() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var response = xmlhttp.responseText;
console.log(response); //<--line 11
if (response != "verified") {
window.location.href = "signin.html";
return false;
} else {
return true;
}
}
}
xmlhttp.open("GET", "scripts/verifySession.php", true);
xmlhttp.send();
return false;
}
And this is the output:
verified session_handler.js:11
verification failed users.php:33
So, you can see that the if condition outputs the string 'verified', and therefore is returning a 'true' result. But the main function is evaluating that to 'false', as evidenced by the string output 'verification failed'. What can I do to correct this?
Thanks!