Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

LaraPhil's avatar

Catch ajax if session has expired

Hi! In my view I have an ajax call like this:

$.ajax({
            type: "POST",
            url: "/savesomething",
            async: false,
            data: {message: "halllo"},
            success : function(data) {
                //show the success message
                showMessage(data.message);
            }                   
});

In my routes file I have a routes group and the route

Route::group(array('before' => 'auth'), function() {
    Route::post('/savesomething', array('uses' => 'SomethingController@savesomething'));
}

Basically that works fine, but the problem is: What happens, if the user loads the site, then the session expires, and then through a user action the ajax post is fired. It does not reach my route because the route is within the route group which has the before "auth"-filter. The user isn't authenticated anymore, because the session has expired.

How can I catch this and redirect the user to my login site? I even have something like this at the end of my routes file:

App::missing(function($exception)
{
    Log::info('This route is missing');
});

But still the ajax post seems to disappear somewhere... Thanks!

0 likes
4 replies
jlrdw's avatar

A post should work the same whether Ajax or regular PHP, so if you had a redirect in that controller method to redirect to login it should work. Test without using Ajax, get it working perfectly then test with AJAX it should work the same way.

jekinney's avatar

@jlrdw unfortunately it's not quite that simple. But good place to start yes.

@LaraPhil the default auth controller checks if Ajax. You probably want to update it from a 404? Return. Then in your Ajax call if the specific error code exists redirect to login page. Unfortunately do to JavaScript being client side laravels redirect or view doesn't work as expected as the page obviously doesn't refresh.

bborisov's avatar

I had the same problem and was able to catch the error like this:

        $.ajax({
            url: xxxx,
            type: "GET",
            success: function(data) {
                $(pageContent).html(data);
            },
            statusCode: {
                401: function() { 
                    window.location.href = 'login'; //or what ever is your login URI 
                }
            },
            error: {
                    //handle error
            }
        }); 

Laravel returns 401 unauthorized.

franzag's avatar

Just add dataSrc: to the ajax call.

ajax: {
	url: '{!! route('xxx') !!}',
	dataSrc: function (myJson) {
		if(myJson == "TIMEOUT"){ 
              	    window.top.location.href = "/login";
              	    return "";
            	}
		return myJson.data;
          },
	 data: function (data) {
              ...
         }

Please or to participate in this conversation.