Landslyde Landslyde - 4 years ago 93
Javascript Question

Is there a better way to check for expired SESSIONS when using JQuery?

I've only been using

for a few weeks. And in this short time I've noticed that, when a SESSION expires, my Login page loads inside the already-loaded document. This was never an issue until I started using JQuery. So I'm thinking that, since I've rewritten all my documents for JQuery to make the calls to PHP, my lone SESSION check is being pulled into the JQuery PHP calls instead of redirecting to the login page. When it does this, a quick page refresh will send the user to the login page. But it sure looks cheesy.

So, my thinking on this (and I hope I'm wrong) is to put

if ($_SESSION["memberid"] == "") {
header("Location: wslogin.php");

inside every PHP block called by JQuery. Maybe this wld be what's now needed since I'm using JQuery. Before JQuery, all my work was inside
tags, and the pages reloaded with every action. And an ended SESSION was always sent to the login page. I'm not the best explainer in the world, but I hope someone understands this and has a solution. Thanks.

Answer Source

Send 401-Unauthorized status code from requested page if session expired. Then capture status code in your client AJAX call.


  data: {},
  dataType: 'json',
  success: function(data) {
    // do whatever here
  type: 'post',
  url: 'load_data.php',
  error: function(XMLHttpRequest, textStatus, errorThrown) {
    // XMLHttpRequest.responseText has your json string
    // XMLHttpRequest.status has the 401 status code
    if (XMLHttpRequest.status === 401) {
      location.href = 'login.php';


header('HTTP/1.1 401 Unauthorized', true, 401);


HTTP Status Codes

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