I wish to authenticate a user each time they click a button. If the user is logged out, and they attempt to click on a button, they are redirected home.
However the code after validate() is executes before the user is redirected home. In this example the popup always displays before the user is directed back home. How do I wait for the execution of validate() to complete before the rest of the event handler attempts to execute?
$("#main-display").on('click', 'button', function (event){
validate();
hello = window.open( '', '', "height = 100, width = 100");
hello.document.write('hello');
});
function validate(){
$.ajax({
url: 'validate_user.php',
dataType: "json",
success: function(response) {
if(response.status == 'false') {
location.href = 'home.php';
}
}
});
}
validate_user.php
<?php
session_start();
if(!isset($_SESSION['userId'])){
session_destroy();
$response['status'] = 'false';
}
else {
$response['status'] = 'true';
}
echo json_encode($response);
?>
EDIT
Thanks for the answers, however the popup still displays before the user is directed back even with the code bits of the most upvoted answers.
You could run your code in the ajax callback instead of directly after you start the request. What the below does is set up your validate function to take a single function parameter. This function is called after the AJAX has been run.
You could even use else on line 14 to only run the code if they are valid users.
This is flexible as it allows validate to be used in different contexts.