Mirian Mirian - 3 years ago 159
Ajax Question

JS redirect after setting a session var with AJAX

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>


And the PHP code that sets the variable:

<?php

session_start();

$v_ip = $_SERVER['REMOTE_ADDR'];
$hash = md5($v_ip);

if(isset($_POST["$hash"])) {

$_SESSION['allow'] = true;

}

?>


On an initial visit to the page, everything is processed correctly and works up to the point of the actual redirect. The session variable is set, the JS code is correctly outputted in the code of the page, and for some weird reason, the actual window.location.replace function is not activated. The page just remains blank - upon inspection the source code displays everything correctly, and yet the redirect does not happen. If I visit the page one more time, the redirect is done fine.

If I change the name of the session variable in both files, and have to re-set it all over again, the same thing happens - upon initial visit the redirect is not processed, but clearly everything up until the actual redirect is processed correctly again.

Why is this happening?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download