简体   繁体   中英

Redirect to login after ajax call if $_SESSION not set

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.

Eg

<?php
require_once globals.php
require_once session.php
?>

<html>
   ...
   <select id="test">
     <option>...

   <script type="text/javascript">
     $('#text').change(function(){
        $.ajax({
             ...
             success: function(result){
                              alert(result);
                      }
             error: ??
       )}
     });
   </script>
<html>

AJAX PHP

<?php
require_once globals.php
require_once session.php

if(isset($_GET['test'])){
      ...
};
?>

MY session.php (which doesn't work with AJAX calls):

<?php
session_start();
ob_start();

if(!$_SESSION['username']){
    header("Location: http://www.mysite.com/login.php");
    die();
}
?>

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

I've tried the following:

in JS:

error: function(XMLHttpRequest, textStatus, errorThrown) {
           if(XMLHttpRequest.status === 401){
               document.location.reload(true);
           }
        },

in session.php

header("Location: http://www.mysite.com/login.php", true, 401);

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.

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.

How can I solve this with a solution that works for both normal and AJAX requests?

Thank you

You can't redirect a user from an AJAX page, you can on the other hand return a value from it that indicates that you should redirect them, and then do so in the return portion of your AJAX call.

Improvement:

I would suggest doing this in your AJAX page:

<?php
require_once globals.php    

if(!isset($_SESSION['username')) {
   echo 'redirectUser';
   exit;
}
if(isset($_GET['test'])){
      ...
};
?>

Then in your AJAX call:

 $('#text').change(function(){
    $.ajax({
         ...
         success: function(result){
                         if(result === 'redirectUser') {
                              window.location.href = 'login.php' //or wherever
                         }else {
                             //success
                         }
                  }
         error: ??
    )}
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM