title: JS redirect after setting a session var with AJAX
body: <p>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.</p>
  
  <p>What I've got so far is:</p>
  
  <pre><code>&lt;?php
  
  $v_ip = $_SERVER['REMOTE_ADDR'];
  $hash = md5($v_ip);
  
  ?&gt;
  
  &lt;html&gt;
  &lt;head&gt;
  &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
  
  &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"&gt;&lt;/script&gt;
  
  &lt;script&gt;
  
  $.ajax({
      type : 'POST',
      url : './session.php',
      dataType: "json",
      data: "&lt;?php echo $hash; ?&gt;",
      success : function(data){},
      error : function(){}
  });
  &lt;/script&gt;
  
  &lt;script&gt;
  
  &lt;?php
  
  if(isset($_SESSION['allow']))  {
  
  echo "var url = \"url-here/?token=\";
        var token = \"token\";
        var redirect = url.concat(token);";
  
  }
  
  ?&gt;
  
  window.location.replace(redirect);
  
  &lt;/script&gt;
  &lt;/head&gt;
  
  &lt;/html&gt;
  </code></pre>
  
  <p>And the PHP code that sets the variable:</p>
  
  <pre><code>&lt;?php
  
  session_start();
  
  $v_ip = $_SERVER['REMOTE_ADDR'];
  $hash = md5($v_ip);
  
  if(isset($_POST["$hash"]))   {
  
  $_SESSION['allow'] = true;
  
  }
  
  ?&gt; 
  </code></pre>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>Why is this happening?</p>