Been working on a project that requires me to perform a JS redirect to a page, by setting up a session variable in PHP via an AJAX query, and then checking to make sure the session is set. After a successful check, the redirect URL would then be constructed in JS and the redirection performed.
What I've got so far is:
<?php
$v_ip = $_SERVER['REMOTE_ADDR'];
$hash = md5($v_ip);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$.ajax({
type : 'POST',
url : './session.php',
dataType: "json",
data: "<?php echo $hash; ?>",
success : function(data){},
error : function(){}
});
</script>
<script>
<?php
if(isset($_SESSION['allow'])) {
echo "var url = \"url-here/?token=\";
var token = \"token\";
var redirect = url.concat(token);";
}
?>
window.location.replace(redirect);
</script>
</head>
</html>
<?php
session_start();
$v_ip = $_SERVER['REMOTE_ADDR'];
$hash = md5($v_ip);
if(isset($_POST["$hash"])) {
$_SESSION['allow'] = true;
}
?>
The first time you go to the page, the session variable isn't set yet. So the if
will fail, and the variable assignments won't be put into the <script>
. The browser will then perform the AJAX call that sets the session variable, but it's too late to affect that original page, you have to go to the page again to see the effect of it.
Remember, all the PHP in the page is executed on the server first, the output is sent to the browser, then the JS is executed.
I suggest you put the code that performs the redirect into the success:
function of $.ajax
.