Andy Groom Andy Groom - 2 years ago 94
jQuery Question

How to deal with a PHP session timeout

I've got an area of a webpage which displays a timesheet and the user can click left and right to go forward / back a week:

<script type="text/javascript">
var TimesheetOffset = 0;
function TimesheetNav(AdjustBy) {
TimesheetOffset = TimesheetOffset + AdjustBy;
$("#timesheets").load("populate_timesheets.php?start=" + TimesheetOffset);
}
</script>


The
populate_timesheets.php
script displays the timesheet information in a DIV area with the id of "timesheets", but only if the user is logged in and their session hasn't expired - if the session has expired it displays a login page:

if (!isset($_SESSION['login_user'])) {
header("location: index.php");
}


The problem is that if the session has timed-out, the
index.php
script appears where the timesheet should be displayed rather than replacing the entire page. How can I alter either the PHP or the JavaScript so that if the session has timed-out the login page replaces the entire page?

Answer Source

JavaScript code:

$.get( "populate_timesheets.php?start=" + TimesheetOffset, function(data) {
  $( "#timesheets" ).html(data);
})
.fail(function() {
  // redirect to login page here, or do something else
})

OR:

$.ajax("populate_timesheets.php?start=" + TimesheetOffset, {
   type: "GET",
   statusCode: {
      401: function (response) {
         // redirect to login page
      }
   }, 
   success: function (data) {
      $( "#timesheets" ).html(data);
   },
   error: function (error) {
      console.log('Error occured: ', error);
   }
});

PHP code:

if (!isset($_SESSION['login_user'])) {
    header("HTTP/1.1 401 Unauthorized");
    return;
}

I don't test this code, so if you have problem, read jQuery documentation about AJAX Requests :)

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