Like most websites, my current project requires users to login. For security reasons, user sessions timeout after a while, leaving the user without an authenticated session. While this is fine for me, it’s not so good for users that may have entered something info a form, hoping to come back to it later. In some cases, the text may be lost – annoying, no doubt.
Since my PHP framework of choice is Laravel, it was relatively simple to have a background process check the user’s login status and, if their session has expired, show an informative message.
Since this article is just a quick demo, I’m going to check the user’s login status every 60 seconds and show the message if nobody is logged in. On the production site this will change, although the method will be the same
$( "li#status" ).timer();
Step 2 – Write the AJAX function that returns the user’s session status.
public function getLoginStatus()
return Response::json( array( ‘status’ => Sentry::check() ) );
/* getLoginStatus */
Step 3 – Setup the timer function that will call the associated AJAX function.
jQuery.fn.timer = function()
$.get( "/ajax/login-status", function( data )
data.status == false ? $( ‘li#status’).show() : $( ‘li#status’).hide();
For the functions above, you may need to alter the way they are called if you aren’t using Laravel in your projects (although I recommend it). You’ll also notice that I’m using Sentry::check() – this is how to check a user’s login status while using the excellent Sentry package from Cartalyst.
Here’s what the <li> element looks like.
That’s really all you need to do, although you may also want to change when the functions are called so that unregistered visitors don’t get shown the message, too. Easy!