Verifying Session Timeout Using AJAX

I have a ColdFusion page, a user can open a modal file and view additional information about a data line. However, if a user sits on a page longer than the default 20-minute session timeout, he will throw an error because he is looking for session variables and cannot find them. I understand how a trap for this is using server-side code, but I cannot get the AJAX call to successfully determine if a session exists.

Here's the AJAX code that fires when the user clicks a button to open a modal. Basically this is checking for a session with a function in CFC. My problem is that it always returns "valid".

//this checks if the session is expired function checkSessionExists() { $.ajax({ //this is the that has function url: 'components/Admin.cfc', //POST method is used type: "POST", //pass the data data: { method: "checkSessionExists" }, async: false, success: function(response) { //$('#loading').hide(); var obj = $.trim(response); if (obj == 'expired') { //it never expired alert('Sorry, your session has expired.') window.location.href = "logout.cfm"; return false; } else{ } }, error: function(jqXHR, exception) { alert('Uncaught Error.\n' + jqXHR.responseText); } }); return false; } 

here is the function in CFC:

 <cffunction name="checkSessionExists" access="remote" output="false" returntype="string" returnformat="plain" hint="I check if session is expired."> <cfif NOT structKeyExists(session, "alive")> <cfreturn "expired" /> <cfelse> <cfreturn "valid" /> </cfif> </cffunction> 

I think that when I ask CFC if there is a session there, it still has session variables because the page has not been refreshed in more than twenty minutes. So ... I wonder how I would send an AJAX request to CFC and have a function in CFC to re-evaluate session variables. Any help would be greatly appreciated!

+7
jquery coldfusion ajax session
source share
1 answer

I will depend on how you configure the session.alive value. Keep in mind that your code will return "valid" while it is alive in the session. If session.valid is configured in the session initialization code, you will get the response you see.

Any request to .cfm will cause the session timeout value to be reset to the current () + session duration. I have used this in the past:

  • Listen to keystrokes or events on the page. If such an event occurs, set the boolean flag
  • Every few minutes, check the value and send an ajax call to keep the session active if the value was true. Then you set the variable to false

Then the cycle repeats. This means that if your users interact with the site, their session will remain open, and at the end of what they do, they will not be thrown out. If the session policy of your business / site allows, this can be a very nice setting.

+4
source share

All Articles