I have a Laravel 9 application that uses vue. I make exteensive use of AJAX calls (through jQuery) in the vue components to fetch the required data. I also use a Javascript timer (setInterval) that makes an Ajax call to fetch updated notifications data. This is my typical Ajax call
$.ajax({
url: "/user/currentUserInfoAndNotifications",
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr(
"content"
),
},
method: "post",
data: {
...
},
dataType: "json",
success: function (data) {
// data received
....
}
}.bind(this),
error: function (data) {
// may happen due to session timeout or other situations..
// How to detect??
}.bind(this),
});
The timer may make a call to thus AJAX call every minute. Meanwhile, the session may timeout and the call will fail.
My question is how to detect timeout or other error conditions in my AJAX calls.
Besides, since my application has 100s of AJAX calls, I would prefer if I can detect this situation at a central place, e.g. routes/web.php (All my routes are contained in this file), so that when ajax makes a call and it comes to routes/web.php, I can detect session timeout situation and logout the user and redirect the user to the session timeout page.
2
Answers
The easiest way to handle session timeout through Laravel is through middlewareGroups in Kernel.php, as given in https://laracasts.com/discuss/channels/laravel/how-to-handle-session-timeout-in-laravel-9-application
You need to modify your
error
callback function like this: