Question

I have build a web site using jquery, css and html. I use ajax calls to retrieve data from flat files on my server and chart them. The problem is that there is an authentication vendor app that user have to authenticate to get to the site. This vendor app has a 30 minute idle time out where if the user does not do anything within 30 minutes, it will time out.

The problem is that when it happens, the page does not go to the login page as it is supposed to.

I thought I need to a server side call to force my page to go though the login page.

I have created this script do a server call to force the page to got the login page, but it does not seem to be working.

Any ideas how I could address this issue? This is my script:

<script>
$(document).ready(function(){
    function continueSession() {
        setTimeout(function(){
            $.get("somepage.php").always(continueSession);
        },30*1000);
    }
continueSession();
});
</script>

somepage.php is a dummy file on the server that does not do anything. Is there a better way do to do this?

Était-ce utile?

La solution

Just check the response code when making ajax requests. If you get an error, send the user to the login page.

$.get("somepage.php").always(function (response) {

  // check response code
  if (response.status !== 200) {

    // did not succeed. redirect to loging page
    window.location.replace("login_page.php");
    return;
  }

  // response is ok
});

You can also use the location header from the response to figure out where to redirect.

$.get("somepage.php").always(function (response) {

    // check if it's a redirect (300 code)
    if (Math.round(response.status / 100.0) * 100 === 300) {

      // redirect to the location header
      window.location.href = response.getResponseHeader("location");
      return;
    }
});

You could do something like this to check on an interval

var checkSession = function () {

  var isRedirect = function (code) {
    return Math.round(code / 100.0) * 100 === 300;
  };

  $.ajax({
    type  : "HEAD", // https://ochronus.com/http-head-request-good-uses/
    async : true,
    url   : "somepage.php",
    success: function (_, _, response) {
      if (isRedirect(response.code)) {
        window.location.href = response.getResponseHeader("location");
      }
    }
  });
};

$(function () {
  // check the session every 30 seconds
  setInterval(checkSession, 30*1000);
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top