php ajax auto logout with timer - php

<script type="text/javascript">
var t;
function startTimer(){
t=setTimeout("document.location='../login/logout.php'", 50000);
}
function stopTimer(){
clearTimeout(t);
}
</script>
This is my script for auto logout,
i want to show the countdown timer, How to create and show the timer,
Also i want to make alive when the user hit the body of the page,
Also timer should reset and then restart again when system is idle,
How to make it,
(Timer should show , that is ,
timer should run when people not touching the system ,
if user touch the system then counter should restart )

Use this function:
function timer(elem, starttime, endtime, speed, funktion, count) {
if (!endtime) endtime = 0;
if (!starttime) starttime = 10;
if (!speed) speed = 1;
speed = speed * 1000;
if ($(elem).html() || $(elem).val()) {
if (count == "next" && starttime > endtime) starttime--;
else if (count == "next" && starttime < endtime) starttime++;
if ($(elem).html()) $(elem).html(starttime);
else if ($(elem).val()) $(elem).val(starttime);
if (starttime != endtime && $(elem).html()) setTimeout(function() {
timer(elem, $(elem).html(), endtime, speed / 1000, funktion, 'next');
}, speed);
if (starttime != endtime && $(elem).val()) setTimeout(function() {
timer(elem, $(elem).val(), endtime, speed / 1000, funktion, 'next');
}, speed);
if (starttime == endtime && funktion) funktion();
} else return;
}
Example
timer("#timer", 50, 0, 1, function() {
location.href = "../login/logout.php";
});

my example:
Updated to check if the user is Idle (is set to 2 seconds, this makes testing easier, i'd recommend at least 5 or 10 minutes).
<body onload="setTimeout('startCountDown()',2000);" onmousemove="resetTimer();">
<form name="counter"><input type="text" size="5" name="timer" disabled="disabled" /></form>
<script type="text/javascript">
<!--
// edit startSeconds as you see fit
// simple timer example provided by Thomas
var startSeconds = 10;
var milisec = 0;
var seconds=startSeconds;
var countdownrunning = false
var idle = false;
document.counter.timer.value=startSeconds;
function CountDown()
{
if(idle == true)
{
if (milisec<=0)
{
milisec=9
seconds-=1
}
if (seconds<=-1)
{
document.location='../login/logout.php';
milisec=0
seconds+=1
return;
}
else
milisec-=1;
document.counter.timer.value=seconds+"."+milisec;
setTimeout("CountDown()",100);
}
else
{
return;
}
}
function startCountDown()
{
document.counter.timer.value=startSeconds;
seconds = startSeconds;
milisec = 0
document.counter.timer.style.display = 'block';
idle = true;
CountDown();
document.getElementById("alert").innerHTML = 'You are idle. you will be logged out after ' + startSeconds + ' seconds.';
countdownrunning = false;
}
function resetTimer()
{
document.counter.timer.style.display = 'none';
idle = false;
document.getElementById("alert").innerHTML = '';
if(!countdownrunning)
setTimeout('startCountDown()',2000);
countdownrunning = true;
}
-->
</script>

my code here...after modified a bit...it works for me...
var startSeconds = 10;
var milisec = 0;
var seconds=startSeconds;
var countdownrunning = false
var idle = false;
document.counter.timer.value=startSeconds;
function CountDown()
{
if(idle == true)
{
if (milisec<=0)
{
milisec=9
seconds-=1
}
if (seconds<=-1)
{
document.location='../login/logout.php';
milisec=0
seconds+=1
return;
}
else
seconds-=1;
setTimeout("CountDown()",1000);
}
else
{
return;
}
}
function startCountDown()
{
seconds = startSeconds;
milisec = 0
idle = true;
CountDown();
document.getElementById("alert").innerHTML = 'You are idle. you will be logged out after ' + startSeconds + ' seconds.';
countdownrunning = false;
}
function resetTimer()
{
idle = false;
if(countdownrunning)
setTimeout('startCountDown()',2000);
countdownrunning = true;
}

Related

How to add day on this js time script?

This is my js/php displaying function:
<script type="text/javascript">
$.fn.cycle.defaults.speed = 900;
$.fn.cycle.defaults.timeout = 5000;
$(function()
{
$('#demos pre code').each(function()
{
eval($(this).text());
});
$('#demos2 pre code').each(function()
{
eval($(this).text());
});
});
$(function($) {
var pstOptions = {
timeNotation: '12h',
am_pm: true,
utc: true,
utc_offset: <%SETTING_TIMEOFFSET%>,
fontFamily: 'Verdana, Times New Roman',
fontSize: '11px',
foreground: 'white',
background: 'black'
}
$('.jclockPST').jclock(pstOptions);
});
</script>
and this is my full js script:
/*
* jQuery jclock - Clock plugin - v 0.2.1
* http://plugins.jquery.com/project/jclock
*
* Copyright (c) 2007-2008 Doug Sparling <http://www.dougsparling.com>
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*/
(function($) {
$.fn.jclock = function(options) {
var version = '0.2.1';
// options
var opts = $.extend({}, $.fn.jclock.defaults, options);
return this.each(function() {
$this = $(this);
$this.timerID = null;
$this.running = false;
$.fn.jclock.getServerOffset($this);
var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
$this.timeNotation = o.timeNotation;
$this.am_pm = o.am_pm;
$this.utc = o.utc;
$this.utc_offset = o.utc_offset;
$this.css({
fontFamily: o.fontFamily,
fontSize: o.fontSize,
backgroundColor: o.background,
color: o.foreground
});
$.fn.jclock.startClock($this);
});
};
$.fn.jclock.getServerOffset = function(el) {
//Want to make a synchronous call to the server to get the server time.
$.ajax({
url: "Time.php",
async: false,
context: el,
success: function(result) {
var serverDate = new Date(+(result) * 1000); //Convert the seconds to a number, and multiple by 1000 to get milliseconds.
var clientDate = new Date();
$this = $(this.context[0]);
$this.serverOffset = clientDate - serverDate; //Set the offset between server and client.
}
});
};
$.fn.jclock.startClock = function(el) {
$.fn.jclock.stopClock(el);
$.fn.jclock.displayTime(el);
};
$.fn.jclock.stopClock = function(el) {
if(el.running) {
clearTimeout(el.timerID);
}
el.running = false;
};
$.fn.jclock.displayTime = function(el) {
var time = $.fn.jclock.getTime(el);
el.html(time);
el.timerID = setTimeout(function(){$.fn.jclock.displayTime(el)},1000);
};
$.fn.jclock.getTime = function(el) {
var now = new Date(new Date().getTime() - el.serverOffset); //Apply the server offset.
var hours, minutes, seconds;
if(el.utc == true) {
if(el.utc_offset != 0) {
now.setUTCHours(now.getUTCHours()+el.utc_offset);
}
hours = now.getUTCHours();
minutes = now.getUTCMinutes();
seconds = now.getUTCSeconds();
} else {
hours = now.getHours();
minutes = now.getMinutes();
seconds = now.getSeconds();
}
var am_pm_text = '';
(hours >= 12) ? am_pm_text = " P.M." : am_pm_text = " A.M.";
if (el.timeNotation == '12h') {
hours = ((hours > 12) ? hours - 12 : hours);
} else {
hours = ((hours < 10) ? "0" : "") + hours;
}
minutes = ((minutes < 10) ? "0" : "") + minutes;
seconds = ((seconds < 10) ? "0" : "") + seconds;
var timeNow = hours + ":" + minutes + ":" + seconds;
if ( (el.timeNotation == '12h') && (el.am_pm == true) ) {
timeNow += am_pm_text;
}
return timeNow;
};
// plugin defaults
$.fn.jclock.defaults = {
timeNotation: '24h',
am_pm: false,
utc: false,
fontFamily: '',
fontSize: '',
foreground: '',
background: '',
utc_offset: 0
};
})(jQuery);
How to add Date on it, so it will display Monday, Tuesday and etc ?
My current time is obtained via time.php via echo time();
Thanks a lot, It will be appreciated.
You can use the Date object's getDay() method to achieve this. getDay() method return 0 ( Sunday ) to 6 ( Saturday ).
You need to build an array first:
var wdays = [ 'Sunday', 'Monday', ... , 'Saturday'] ;
Then get the week day name by :
var weekday = wdays[now.getDay()];
timeNow += weekday; //append week day to the final result
function day() {
var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var now = new Date();
return days[now.getDay()];
}
now you can call the day function to get date in string var today = day() // 'Tue' or current day

Running multiple functions javascript

I currently have a table that is being populated by a MySQL table, in turn i want to take the data from these cells and use them to create a simulated real time update, i have it working however due to having multiple rows im using for loops in the javascript functions and i believe this is causing the other functions not to run and i cannot figure out a way round it.
Javascript Code:
var seconds = 5;
var divid = "status";
var url = "boo.php";
var timeout;
function refreshdiv(){
// The XMLHttpRequest object
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Your browser does not support AJAX.");
return false;
}
}
}
// Timestamp for preventing IE caching the GET request
fetch_unix_timestamp = function()
{
return parseInt(new Date().getTime().toString().substring(0, 10))
}
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;
// The code...
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById(divid).innerHTML=xmlHttp.responseText;
setTimeout('refreshdiv()',seconds*1000);
}
}
xmlHttp.open("GET",nocacheurl,true);
xmlHttp.send(null);
}
// Start the refreshing process
var seconds;
window.onload = function startrefresh(){
setTimeout('refreshdiv()',seconds*1000);
}
function runningtime(int) {
if(int == 0) { //if there is data
console.log("int=0 so no data is present, int: " + int);
} else if(int == 1){
var isRunning = new Array();
isRunning[0] = " ";
for (var i=0; i < 3; i++) {
var bool = 'running' + i;
console.log("Running = " + bool);
running = document.getElementById(bool).innerHTML.substring(10,11);
console.log("running: " + running);
if(isRunning[i] == "1") {
var time = 'Time' + i;
a= document.getElementById(time).innerHTML;
console.log("a= " + a);
hour=a.substring(0,2);
min= a.substring(3,5);
sec= a.substring(6,8);
sec==sec++;
if (min<=9) { min="0"+min; }
if (sec<=9) { sec="0"+sec; }
time = (hour + ":" + min + ":" + sec + " ");
if (document.getElementById) { document.getElementById(time).innerHTML = time; }
else if (document.layers) {
document.layers.theTime.document.write(time);
document.layers.theTime.document.close(); }
} else {
//Do nothing
return;
}
}
timeout = setTimeout("runningtime(1)", 1000);
}
}
function experiencehour(exp) {
if(exp == 0) { //if there is dexphourtexphour
console.log("exp=0 so no data is present, exp: " + exp);
} else if(exp == 1){
var isRunning = new Array();
isRunning[0] = " ";
for (var i=0; i < 3; i++) {
var bool = 'running' + i;
console.log("Running = " + bool);
running = document.getElementById(bool).innerHTML.substring(10,11); //checks if bot running
console.log("running: " + running);
if(isRunning[i] == "1") {
var exph = 'Exph' + i;
var expg = 'Exp' + i;
exphour = document.getElementById(exph).innerHTML; //exphour
currexp = document.getElementById(exp).innerHTML; //current gained exp
exphour =parseInt(exphour);
currexp =parseInt(currexp);
console.log("currexp= " + currexp);
console.log("exphour= " + exphour);
expmin = exphour/60;
console.log("expmin= " + expmin);
expsec = Math.round(expmin/60);
console.log("expsec= " + expsec);
newtotalexp = currexp + expsec;
console.log("newtotalexp= " + newtotalexp);
if (document.getElementById) { document.getElementById(exp).innerHTML = newtotalexp; } //writing new exp
else if (document.lexphouryers) {
document.lexphouryers.theTime.document.write(time);
document.lexphouryers.theTime.document.close(); }
} else {
//Do nothing
return;
}
}
timeout = setTimeout("experiencehour(1)", 1000);
}
}
function variable1hour(var1) {
if(var1 == 0) { //if there is dvar1hourtvar1hour
console.log("var1=0 so no data is present, var1: " + var1);
} else if(var1 == 1){
var isRunning = new Array();
isRunning[0] = " ";
for (var i=0; i < 3; i++) {
var bool = 'running' + i;
console.log("Running = " + bool);
isRunning[i] = document.getElementById(bool).innerHTML.substring(10,11); //checks if bot running
console.log("isRunning = " + isRunning[i]);
if(isRunning[i] == "1") {
var varh = 'Varh' + i;
var varg = 'Var' + i;
console.log("Varh = " + varh);
console.log("Var = " + varg);
var1hour = document.getElementById(varh).innerHTML; //var1hour
currvar1 = document.getElementById(varg).innerHTML; //current gained var1
var1hour =parseInt(var1hour);
currvar1 =parseInt(currvar1);
console.log("currvar1= " + currvar1);
console.log("var1hour= " + var1hour);
var1min = var1hour/60;
console.log("var1min= " + var1min);
var1sec = Math.round(var1min/60);
console.log("var1sec= " + var1sec);
newtotalvar = currvar1 + var1sec;
console.log("newtotalvar= " + newtotalvar);
if (document.getElementById) { document.getElementById(varg).innerHTML = newtotalvar; } //writing new var1
else if (document.lvar1houryers) {
document.lvar1houryers.theTime.document.write(time);
document.lvar1houryers.theTime.document.close();
}
} else {
//Do nothing
return;
}
}
timeout = setTimeout("variable1hour(1)", 1000);
}
}
function stopScript() {
console.log("Stopping script");
clearTimeout(timeout);
}
function startScript(i) {
variable1hour(i);
experiencehour(i);
runningtime(i);
}
Any ideas on how i can get around this so i can get all 3 functions running simultaneously.
I have checked console and im not getting any errors that would stop them from running.
You can't have simultaneously in JS. But you can simulate simultaneous a bit in JS.
Take a look at underscore's defer method.
http://underscorejs.org/#defer
It'd work like this:
Take the loop body and wrap it up in a function
Each iteration through the for loop, make a call to the function using defer
That's basically it. Doing that will allow other functions to "interrupt" any given process (function) and thus "share" the execution thread.
A standard JS implementation w/out defer. I'm trying to simulate the closer of defer. The key takeaway here is that, while the calls still execute in the order that they were queued, all get "started" before any one of them completes. In the case of AJAX async requests, the async response should be able to inject itself between any two loop iterations. You can also set data processing by using slight delays
http://jsfiddle.net/t2z9A/
for(var i = 0; i != 5; ++i)
{
(function(index)
{
document.getElementById('id' + index).innerHTML = 'started...';
setTimeout(function()
{
// kill some time
var str = '';
for(var j = 0; j != 10000000; ++j)
str = str + ' ';
document.getElementById('id' + index).innerHTML = 'Function: 1. Index: ' + index + ' - ' + new Date().getTime();
}, index);
})(i);
}
for(var i = 5; i != 10; ++i)
{
(function(index)
{
document.getElementById('id' + index).innerHTML = 'started...';
setTimeout(function()
{
// kill some time
var str = '';
for(var j = 0; j != 1000000; ++j)
str = str + ' ';
document.getElementById('id' + index).innerHTML = 'Function: 2. Index: ' + index+ ' - ' + new Date().getTime();
}, 1);
})(i);
}

why is this jQuery not working?

I'm having this jQuery script thats adding a timer when someone voted he needs to wait 3 minutes
the script is working till the moment I'm getting the remaining time with php
$(document).ready(function(){
alert("1");
function Timer(dur, par, can, cnt) {
var parent = $(par),
canvas = can ? $(can, parent)[0] : $('.timer', parent)[0],
seconds = cnt ? $(cnt, parent)[0] : $('.counter', parent)[0],
sec = dur,
countdown = sec;
if (!canvas)
canvas = $("<canvas>").addClass('timer')
.attr('width', 100).attr('height', 100).appendTo(parent)[0];
if (!seconds)
seconds = $("<span>").addClass('counter').appendTo(parent)[0];
var ctx = canvas.getContext('2d');
ctx.lineWidth = 8;
ctx.strokeStyle = "#528f20";
var startAngle = 0,
time = 0,
intv = setInterval(function() {
var endAngle = (Math.PI * time * 2 / sec);
ctx.arc(65, 35, 30, startAngle, endAngle, false);
ctx.clearRect(0, 0, 200, 200);
startAngle = endAngle;
ctx.stroke();
countdown--;
if (countdown > 60) {
seconds.innerHTML = Math.floor(countdown / 60);
var ss = countdown % 60;
if (ss < 10)
ss = "0" + ss;
seconds.innerHTML += ":" + ss;
}
else {
seconds.innerHTML = countdown;
}
if (++time > sec, countdown == 0) {
clearInterval(intv);
$(canvas).remove();
$(seconds).remove();
/*$(par).prepend('<img id="theImg" src="http://ivojonkers.com/votify/upvote.png" />');*/
}
}, 1000);}
$(".upvote").click(function(){
alert("2");
var par = $("<div>").addClass("time").appendTo("#timers");
Timer(Math.round(180), par);
});
if (<?php echo $wait; ?> > 0) {
var par = $("<div>").addClass("time").appendTo("#timers");
Timer(Math.round(<?php echo $wait; ?>, par); } });
so in this part I'm getting the time to wait for the next vote with php and this does not seem to work what's going wrong ?
if (<?php echo $wait; ?> > 0) {
var par = $("<div>").addClass("time").appendTo("#timers");
Timer(Math.round(<?php echo $wait; ?>, par); } });
You should just use a setTimeout(function(){},(3 * 60 * 1000)) to block the vote functionality.
//Block the vote here
setTimeout(function(){/*unblock here*/},(3 * 60 * 1000))
Replace this:
Timer(Math.round(<?php echo $wait; ?>, par); } });
With:
Timer(Math.round(<?php echo $wait; ?>, par)); } });
;)

Capture javascript stopwatch stop time and store it as php variable

I'm using this stopwatch:
<script language="JavaScript" type="text/javascript">
window.onload = function()
{
stopwatch('Start');
}
<!--
var sec = 0;
var min = 0;
var hour = 0;
function stopwatch(text) {
sec++;
if (sec == 60) {
sec = 0;
min = min + 1; }
else {
min = min; }
if (min == 60) {
min = 0;
hour += 1; }
if (sec<=9) { sec = "0" + sec; }
document.clock.stwa.value = ((hour<=9) ? "0"+hour : hour) + " : " + ((min<=9) ? "0" + min : min) + " : " + sec;
if (text == "Start") { document.clock.theButton.value = "Stop "; }
if (text == "Stop ") { document.clock.theButton.value = "Start"; }
if (document.clock.theButton.value == "Start") {
window.clearTimeout(SD);
return true; }
SD=window.setTimeout("stopwatch();", 1000);
}
function resetIt() {
sec = -1;
min = 0;
hour = 0;
if (document.clock.theButton.value == "Stop ") {
document.clock.theButton.value = "Start"; }
window.clearTimeout(SD);
}
// -->
</script>
and would like to capture the time that the clock is stopped on, and then store it as a PHP variable so that I can insert it into our database along with a load of other PHP variables. Is this possible?
Thanks for any help
Spice up your code with some AJAX. Inside of function resetIt() pass the current timestamp to your php script.
jQuery has a solid AJAX part and nice documentation with examples too.
(Assuming jQuery loaded, up and running)
function resetIt() {
$.ajax({
url: 'your.php',
success: function(response){
alert(response);
}
});
sec = -1;
min = 0;
hour = 0;
if (document.clock.theButton.value == "Stop ") {
document.clock.theButton.value = "Start"; }
window.clearTimeout(SD);
}
your.php (since all you need to save the actual timestamp we won't pass any variable to the PHP part. If you need to add specific variables (from JS) you can add them, of course)
if(mysql_query("INSERT INTO `database` (`stopped`) VALUES (NOW())")) {
echo 'success';
} else {
echo 'failed';
}
die();

Time counter with JavaScript or PHP

I want to implement a time counter with JavaScript or PHP. I did some looking on Google and tried it, but didn't get the output I need.
Users will enter the time in the textbox provided, then I need to give them a counter from the time they entered.
Example: If I enter 1:27:38 and click on submit, the time should decrease and I should get an alert when it reaches 0.
How can I implement this?
In JavaScript:
<html>
<head>
</head>
<body>
<script language="JavaScript">
<!-- //
var timeleft;
var nextdue;
var tick = 1000;
function parseTime(t) {
var tt = ("0:00:"+t);
tt = tt.split(":").reverse();
return (tt[0] * 1000)+(tt[1] * 60000)+(tt[2] * 3600000);
}
function zeroPad(n) {
if (n<10) return "0"+n;
return ""+n;
}
function makeTime(t) {
if (t<0) return "0:00:00";
var tt=t+999;
return Math.floor(tt/3600000)+":"+
zeroPad(Math.floor(tt/60000)%60)+":"+
zeroPad(Math.floor(tt/1000)%60);
}
function startTimer() {
nextdue = new Date().getTime();
timeleft = parseTime(document.timerform.timerbox.value);
runTimer();
}
function runTimer() {
document.timerform.timerbox.value=makeTime(timeleft);
if (timeleft<=0) alert ("Time's up!");
else {
var timecorr = (new Date().getTime())-nextdue;
if (timecorr>0 && timecorr<3000) {
timeleft -= (tick+timecorr);
nextdue += tick;
if (timeleft<1) setTimeout ("runTimer()",tick+timeleft);
else setTimeout("runTimer()",Math.max(1,tick-timecorr));
}
else {
nextdue=(new Date().getTime())+tick;
timeleft-=tick;
if (timeleft<1) setTimeout ("runTimer()",tick+timeleft);
else setTimeout("runTimer()",tick);
}
}
}
// -->
</script>
<form name="timerform">
Decimal places: <input type="text" name="timerbox" value="0:00:00"></input>
<input type="button" value="Start timer" onClick="startTimer()"></input>
</form>
</body>
</html>
In PHP:
list($hours, $minutes, $seconds) = explode(':', $_POST['time']);
$seconds = $hours * 3600 + $minutes * 60 + $seconds;
for ($i = $seconds; $i > 0; $i--)
{
echo $i;
sleep(1);
flush();
}
echo 'Countdown finished.';

Categories