Ajax call in timed out session

I have a lot of views loaded through Ajax calls.
They all work perfectly.

But when session ends, the login page is loaded in the Ajax layout.
And sometimes, I can’t login in those windows (depending of the script).

How can I force load the login page in the top window ?

How is the output of your Ajax calls being inserted into your page?

With jQuery : $("#my_div").load(‘admin/controller/action’);

You’ll need to start with some change to your authentication setup, to return something (e.g. a different HTTP status code) instead of redirecting on an authentication error for Ajax calls. Exactly how to do that part would very much depend on many details of your current implementation, but that’s the general gist of it.

Then, the load method can accept a callback parameter. I’m no jQuery expert, so can’t say for sure, but I think that you could catch the status in that function and redirect the page at that point.

Thank you for showing me the way.

I thought I had to do something in the beforeFilter() of the controllers but it did not work.

So it is very easy now :

$("#my_div").load(url, function (response, status, xhr) {
                    if ( status == "success" ) {
                        // do something
                    } else {
                        window.location.href = "redirect_url";
                    }
                })

And when I do not use jQuery it is the same in vanilla js with success and error callbacks.

Thank you.

After some time dealing with this problem, it happens that the solution I gave does not work most of the time.
First, the request does not always return an error (in fact, most of the time not).
Second, when doing this this, you cannot catch another error and, if needed, cannot track any other problem.
So I ended to do that : (in UsersController → login)

if ($this->request->is('ajax')) {
            return $this->redirect($this->referer());
        }

Redirecting to the referer ends up loading the login page if you are no longer connected.

I’ve been doing this for more than a week now and had no problem.

Hope it helps.