1

I have an AJAX form that does some authentication of the data. If the session timed out I want to redirect to login page. How can I achieve that? Here is my simplified server side code:

function doExecute(Request $request){
    if (isset($_SESSION["user_id"])){
        $user = New User($_SESSION["user_id"]);
        $returnData["cashBack"] = $user->getAvailCashBack();
        echo json_encode($returnData);

    }
} 

here is my jquery ajax call code:

$.post('index.php?cmd=hx_cash',function(data){
        var cashBack= data["cashBack"];
        //somecode;
}

What do i need to add to either the server side or browser side code to achieve the redirect to login page if the session is timed out?

user2395238
  • 850
  • 1
  • 9
  • 20

1 Answers1

1
function doExecute(Request $request){
    if (isset($_SESSION["user_id"])){
        $user = New User($_SESSION["user_id"]);
        $returnData["cashBack"] = $user->getAvailCashBack();
        echo json_encode($returnData);

    }else echo "{\"logout\":\"<login url>\"}";
} 
$.post('index.php?cmd=hx_cash',function(data){
   if(data.logout){
      location.href = data.logout;
      return;
   }     
   var cashBack= data["cashBack"];
    //somecode;
}

In your PHP code send the url where you want the user to be only if session is not set, and before every call you can redirect to login page if session not set before handling your ajax business logic

joyBlanks
  • 6,419
  • 1
  • 22
  • 47