title: Redirect to login after ajax call if $_SESSION not set
body: <p>I have a 'check session' page included on each page I want a $_SESSION is set. This means the 'check session' script is included also on ajax/php pages.</p>
  
  <p>E.g.</p>
  
  <pre><code>&lt;?php
  require_once globals.php
  require_once session.php
  ?&gt;
  
  &lt;html&gt;
     ...
     &lt;select id="test"&gt;
       &lt;option&gt;...
  
     &lt;script type="text/javascript"&gt;
       $('#text').change(function(){
          $.ajax({
               ...
               success: function(result){
                                alert(result);
                        }
               error: ??
         )}
       });
     &lt;/script&gt;
  &lt;html&gt;
  </code></pre>
  
  <p>AJAX PHP</p>
  
  <pre><code>&lt;?php
  require_once globals.php
  require_once session.php
  
  if(isset($_GET['test'])){
        ...
  };
  ?&gt;
  </code></pre>
  
  <p>MY session.php (which doesn't work with AJAX calls):</p>
  
  <pre><code>&lt;?php
  session_start();
  ob_start();
  
  if(!$_SESSION['username']){
      header("Location: http://www.mysite.com/login.php");
      die();
  }
  ?&gt;
  </code></pre>
  
  <p>This script redirects me to login.php if $_SESSION is not set only when I load a page normally, but in case of AJAX calls, the JS AJAX function returns error but I'm not able to redirect the user to login.php</p>
  
  <p>I've tried the following:</p>
  
  <p>in JS:</p>
  
  <pre><code>error: function(XMLHttpRequest, textStatus, errorThrown) {
             if(XMLHttpRequest.status === 401){
                 document.location.reload(true);
             }
          },
  </code></pre>
  
  <p>in session.php</p>
  
  <pre><code>header("Location: http://www.mysite.com/login.php", true, 401);
  </code></pre>
  
  <p>This returns a 401 code to JS, and JS reload the current page, calling again session.php which should now normally redirect to login.php.</p>
  
  <p>But it doesn't: with this solution even if I load a page normally without $_SESSION set, I get a blank page. The script die() but doesn't redirect.</p>
  
  <p>How can I solve this with a solution that works for both normal and AJAX requests?</p>
  
  <p>Thank you</p>