jQuery: inactivity refresh/logout - javascript

I am using the below jQuery to refresh my datatable. I know there is a better way to do this, but for the time being, this is what is working for me:
var idleTime = 0;
var idleInterval = setInterval(funcion(){
idleTime = idleTime + 1;
if (idleTime > 1)
{
$('#example1').DataTable().state.clear();
window.location.reload();
}
}, 60000);
$(this).mousemove(function(e){
idleTime = 0;
});
$(this).keypress(function(e){
idleTime = 0;
});
Using the above code, after about 1 minute, the page will clear the datatable and reload the page.
Is there something that I can add to the code that will look at how many times it has refreshed due to inactivity? And then after 120 refreshes, log the user out.
I am not sure if this can be done being that the page keeps refreshing.

You need a way to keep track of the number of reloads between reloads. Since you reload the entire page I can quickly think of two ways:
1) use cookies to keep the number and reset the cookie properly if there is activity
2) use parameters to send the value to the server and let the server insert it back into your javascript
That is if you want to handle this in javascript.
Normally you handle a logout in the server side session. Then you have to make sure your auto reload is not identified by the server as "activity".
Hope this helps...

I have well like to offer you a simple solution, but as long as you use jquery already better enjoy it with using ajax.
var idleTime = 0;
var idleInterval = setInterval(funcion(){
idleTime = idleTime + 1;
if (idleTime > 1)
{
var url = window.location.href + 'page_table.php';
//you should specify a page_table.php that return only the table.
$.get(url, function( data ) {
$('#example1').html(data); //<----- refresh only the zone with the id : #example
$('#example1').DataTable(); // <---- important : set the element as DataTable.
});
}
}, 60000);
$(this).mousemove(function(e){
idleTime = 0;
});
$(this).keypress(function(e){
idleTime = 0;
});
the idea is to refresh only the part of table.

Let's keep the current code that you have if it works for you, and let's not depend on localStorage, or additional tricks that might or might not work depending on the browser. Let's store the information in the url.
Like this:
var idleTime = 0,
refreshCount = window.location.hash ?
Number(window.location.hash.replace("#", '')) : 0; //get current counter
var idleInterval = setInterval(function(){
//...all your existent code
/*let's rewrite the url with our new counter, so now when the
page is reloaded and th script is executed it gets the new value */
if(refreshCount == 60) {
//do your magic it has been refreshed 60 times
} else {
window.location = window.location.href.replace('#' + refreshCount, '')
+ '#' + (refreshCount+1);
window.location.reload();
}
}, 1000);
Hope this helps.
Cheers.

Related

Need to clear session and logout user after 30 sec or after close browser

code is in MVC and also every request are using ajax call so no change in url.
using below code i ll able to perform firt opration that logout user if user inactive of 30 sec. but not able to perform action when user logout.
<script>
$(function () {
$("body").on('click keypress', function () {
ResetThisSession();
});
});
var timeInSecondsAfterSessionOut = 30; // to change the session time out, change this value. Must be in seconds.
var secondTick = 0;
function ResetThisSession() {
secondTick = 0;
}
function StartThisSessionTimer() {
secondTick++;
console.log(secondTick);
if (secondTick > timeInSecondsAfterSessionOut) {
clearTimeout(tick);
window.location = '/Account/LogOff/0';
}
tick = setTimeout("StartThisSessionTimer()", 1000);
}
StartThisSessionTimer();
</script>
alse i tried the unload or beforeunload method of script but result not proper as expect.
need to logout user if user not perform any action on 30 sec or if user close browser.
thanks in advance.
as i see the var tick is local, and is defined in every tick, so the timeout is called every second:
function StartThisSessionTimer() {
secondTick++;
console.log(secondTick);
if (secondTick > timeInSecondsAfterSessionOut) {
clearTimeout(tick);
window.location = '/Account/LogOff/0';
}
tick = setTimeout("StartThisSessionTimer()", 1000);
}
Try to separate the initializiaton of the timeout, outside of the same scope of repeater of timeout.
tell us if is useful.
Tks

Target page refresh either by javascript or PHP

I am trying to figure out how can I refresh a target page when visited either by a hyperlink or the back button, or even a button. Any ideas ? I have tried almost any solution I could find online and still can make the target page refresh after visited.
Well you can refresh the page using JavaScript with this code:
location.reload();
But if you don't put a condition on it, it'll refresh forever, right?
You'll need to describe your issue in more detail.
if you want to reload page when page full loaded use this JS:
$( document ).ready(function() {
location.reload();
});
if you want timer when page loaded and then reload it use:
$( document ).ready(function() {
// reload after 5 second
setTimeout(function() {
location.reload();
}, 5000);
});
if you want reload only first time use this:
function setCookie(cookieName,cookieValue,nDays) {
var today = new Date();
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString();
}
function getCookie(cookieName) {
var theCookie=" "+document.cookie;
var ind=theCookie.indexOf(" "+cookieName+"=");
if (ind==-1) ind=theCookie.indexOf(";"+cookieName+"=");
if (ind==-1 || cookieName=="") return "";
var ind1=theCookie.indexOf(";",ind+1);
if (ind1==-1) ind1=theCookie.length;
return unescape(theCookie.substring(ind+cookieName.length+2,ind1));
}
So, you would tie it together like this:
$(function() {
var skipModal = getCookie('skipModal');
if (!skipModal) { // check and see if a cookie exists indicating we should skip the modal
// show your modal here
setCookie('skipModal', 'true', 365*5); // set a cookie indicating we should skip the modal
}
});
show this link:
Fire jquery script on first page load, and then never again for that user?

how to keep the session active even i opened in multiple tabs in same browser

i would like to implement one thing.i opened my site in multiple tabs. while i work in one tab others tabs should not be timedout. it should be alive. how to keep alive for other tabs. i used below js to find idle time logout.
<script type="text/javascript">
idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
var idleInterval = setInterval("timerIncrement()", 60000); // 1 minute
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
})
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 2) { // 30 minutes
var beforeTime = new Date()
var bminutes = beforeTime.getMinutes();
var bseconds = beforeTime.getSeconds();
var user='<?php echo Auth::getSessionUserFullName();?>';
if(user!='')
{
var timehours=beforeTime.getHours();
var timeoutmin=bminutes+1;
var timeoutseconds=bseconds-1;
if(timeoutseconds>59)
{
timeoutseconds=0;
timeoutmin=timeoutmin+1;
}
if(timeoutmin>59)
{
timeoutmin=0;
timehours=hours+1;
}
if(timehours>24)
{
timehours=0;
}
var ok=confirm("Your session expire time started at "+beforeTime.getHours()+":"+beforeTime.getMinutes()+":"+beforeTime.getSeconds()+".Please click 'OK' before "+timehours+":"+timeoutmin+":"+timeoutseconds+" to stay signed in.");
if(ok)
{
var currentTime = new Date()
var aminutes = currentTime.getMinutes();
var aseconds = currentTime.getSeconds();
var time=aminutes-bminutes;
if(aminutes>bminutes && aseconds>bseconds)
{
alert('Time out!!Please login again to access.');
window.location.href='<? echo APPLICATION_WEBROOT?>auth/logout';
return false;
}
else if(time>=2)
{
alert('Time out!!Please login again to access.');
window.location.href='<? echo APPLICATION_WEBROOT?>auth/logout';
return false;
}
else
{
return true;
}
}
else
{
window.location.href='<? echo APPLICATION_WEBROOT?>auth/logout';
}
}
}
}
</script>
Please help me. how to keep the sessions for all opened tabs.thanks in advance
The session is not tab specific. It is for the whole browser instance.
The session is extended when a user makes a request to the server. So depending on your application, you may have to generate regular requests to the server to extend that session.
For that, you can use the setInterval javascript function to trigger an AJAX call to your PHP backend.
Hope that helps...
BTW: be careful because some browsers do deactivate the tabs which don't have the user focus (Chrome for example) - it will not modify session... but some JS could be suspended.
One of the way I can think of is handle the session yourself in the server.
Here's a system that might work (welcome suggestions of improvement):
1) store your own custom session in server DB, with IP being the unique identifier.
2) whenever user interacts with your server, grab its IP and update the corresponding session stored in server. If that session has already timeout, redirect user to timeout page.
there might be many things that I haven't though through, but in my mind this should be a viable way to maintain session across tabs

function is looped according to setinterval but with different parameters

i have a simple question, there is a function with parameter emp_id that opens up a form for a chat with different attributes, i want it to be refreshed automatically each 10 sec, now it works a bit wrongly, since there is a parameter emp_id that is can be changed, and once i change it, the chat with messages and form are refreshed double time or triple times :) depend on how many times u change the emp_id, i hope i was clear )) anyway here is the javascript function:
function load_chat(emp_id) {
var url = "#request.self#?fuseaction=objects2.popup_list_chatform"
url = url + "&employee_id=" + emp_id;
document.getElementById('form_div').style.display = 'block'; AjaxPageLoad(url,'form_div',1,'Yükleniyor');
setInterval( function() {
load_chat(emp_id);
},10000);
}
there a list of names, once i click on one of them, this form is opened by this function, but if i click another user, i mean if i change the emp_id, it refreshes, the previous and present form. how do i change it so that it will refresh only the last emp_id, but not all of id's which i've changed
thank you all for the help, i really appreciate it!
This would nicely encapsulate what you're doing. The timer id (tid) is kept inside the closure, so when you call load_chat it will stop the interval if there was one running.
Once the new url is set up, it will start the interval timer again.
var ChatModule = (function() {
var tid,
url;
function refresh()
{
AjaxPageLoad(url, 'form_div', 1, 'Yükleniyor');
}
return {
load_chat: function(emp_id) {
if (tid) {
clearInterval(tid);
}
// setup url
url = "#request.self#?fuseaction=objects2.popup_list_chatform"
url = url + "&employee_id=" + emp_id;
document.getElementById('form_div').style.display = 'block';
// load ajax
refresh();
// set timer
tid = setInterval(refresh, 10000);
}
}
}());
ChatModule.load_chat(123);
Use setTimeout instead. Each time your function is executed, it will set up the next execution (you could also make it conditional):
function load_chat(emp_id) {
... // do something
if (condition_still_met)
setTimeout(function() {
load_chat(emp_id); // with same id
}, 10000);
}
load_chat("x"); // to start
Or you will have to use setInterval outside the load_chat function. You can clear the interval when necessary.
function get_chat_loader(emp_id) {
return function() {
... // do something
};
}
var id = setInterval(get_chat_loader("x"), 10000); // start
// then, somewhen later:
clearInterval(id);

How to kill a javascript redirect if button is pressed?

I have come up with the following code, which allows users to view a page with a movie embed for 30 seconds before redirecting them away from the page. Additionally, they can click a link to hide the div with this countdown. What I need help with is canceling the redirect (stopping it from happening) if that link is clicked, so users can continue to watch the full movie. Thanks in advance for your help!
Javascript:
<script type="text/javascript">
var settimmer = 0;
$(function(){
window.setInterval(function() {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter)- eval(1);
$("b[id=show-time]").html(updateTime);
if(updateTime == 0){
window.location = ("redirect.php");
}
}, 1000);
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$(".slidingDiv").show();
$(".show_hide").show();
$('.show_hide').click(function(){
$(".slidingDiv").slideToggle();
});
});
</script>
HTML:
<div id="my-timer" class="slidingDiv">
You have <b id="show-time">30</b> seconds to decide on this movie.
Yes, I want to watch this one!
</div>
setInterval returns a value you can use to cancel the interval timer via clearInterval. So:
$(function(){
// +--- Remember the value from `setInterval
// |
// v
var timerHandle = window.setInterval(function() {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter)- eval(1);
$("b[id=show-time]").html(updateTime);
if(updateTime == 0){
window.location = ("redirect.php");
}
}, 1000);
// + Hook up a handler for the link that uses the handle to clear it
// |
// v
$("selector_for_the_link").click(function() {
clearInterval(timerHandle);
timerHandle = 0;
});
});
Note that I've put the variable inside your ready function, so it isn't a global.
Off-topic: You don't need or want to use eval in the above (in fact, you virtually never want to use eval at all, for anything). If you want to parse a string to make a number, use parseInt (and there's never any reason to eval a literal like 1). So this line:
var updateTime = eval(timeCounter)- eval(1);
becomes
var updateTime = parseInt(timeCounter, 10) - 1;
(The 10 means the string is in decimal — e.g., base 10.)
You need to use the clearInterval method.
Maybe you can use setTimeout() to do so rather than setInterval().Here is a sample.

Categories