Javascript countdown timer that stops when window is not in focus - php

Ok , I'm having trouble to solve this , I'm a php / C# web developer , and have no experience or knowledge in Javascript, I have to do just this one thing that needs Javascript:
When a certain page loads, a counter starts. The client must stay on this page for 20 seconds. after, I want to execute php code.
So there are 2 issues concerning me, first: how do I stop the counter, if client leaves the page (meaning the page is not in focus).
2) How can I execute php in javascript? , or call a php function from Javascript.
The code I have so far is this:
<html>
<head>
</head>
<body>
<div id='timer'>
<script type="text/javascript">
COUNTER_START = 20
function tick () {
if (document.getElementById ('counter').firstChild.data > 0) {
document.getElementById ('counter').firstChild.data = document.getElementById ('counter').firstChild.data - 1
setTimeout ('tick()', 1000)
} else {
document.getElementById ('counter').firstChild.data = 'done'
}
}
if (document.getElementById) onload = function () {
var t = document.createTextNode (COUNTER_START)
var p = document.createElement ('P')
p.appendChild (t)
p.setAttribute ('id', 'counter')
var body = document.getElementsByTagName ('BODY')[0]
var firstChild = body.getElementsByTagName ('*')[0]
body.insertBefore (p, firstChild)
tick()
}
</script>
</div>
</body>
</html>
and I also want the timer to start ticking when the client gets back on page
Thank you very much for ur help in advance

You could do this using jQuery.
Recycling an old Stackoverflow post, try this:
var window_focus;
var counter = 1000;
// on focus, set window_focus = true.
$(window).focus(function() {
window_focus = true;
});
// when the window loses focus, set window_focus to false
$(window).focusout(function() {
window_focus = false;
});
// this is set to the ('click' function, but you could start the interval/timer in a jQuery.ready function: http://api.jquery.com/ready/
$(document).one('click',function() {
// Run this function every second. Decrement counter if window_focus is true.
setInterval(function() {
$('body').append('Count: ' + counter + '<br>');
if(window_focus) { counter = counter-1; }
}, 1000);
});
Demo and old post
DEMO | Old So post
Update
Probably because the demo runs in 4 iframes, the $(window).focus bit only works on the iframe actually running the code (the bottom-right window).
jQuery
jQuery.com (How jQuery works) | Example (back to basics halfway down the page) | If you use the 2nd link, also read this

In regards to your first question about detecting if the window is out of focus, see this answer: Is there a way to detect if a browser window is not currently active?
It is possible, but only very new browsers support this so it may not be useful based on current browser support.
To trigger PHP code from Javascript, you would have to make an AJAX call to a server-side PHP script to invoke PHP since JS is client-side and PHP is server-side.

Related

jquery .load function running more than once

I'm trying to implement SEO friendly infinite scrolling in accordance with google's recommendations as seen here (http://scrollsample.appspot.com/items?page=7). I have a jquery function that sends a request to a php file, (which requests the data from the db) anytime someone scrolls to the bottom of the page, now everything is working fine except that when the user scrolls to the bottom of the page, the request function gets fired more than once. So duplicate entries of the data gets loaded into the page, now i know this isn't from my php file because i opened the page directly in my browser and everything was fine. Checkout the bug here http://devx.dx.am/haze/categor.php?artemis=foo&&page=1
I have already tried the solutions here (jQuery .load() callback function fires multiple times) and here ($(window).load() is executing 2 times?) and a few others as well.
$(window).bind('scroll', function() { //#cagorwrap is the div that should contain the data retrieved
if($(window).scrollTop() >= $('#cagorwrap').offset().top + $('#cagorwrap').outerHeight() - window.innerHeight) { //344.6
var queryParameters = {}, queryString = location.search.substring(1),
re = /([^&=]+)=([^&]*)/g, m;
while (m = re.exec(queryString)) {
queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
var url2 = "modules/paginate.php?numpages=set";
// #rc is a hidden div too
$("#rc").load(url2, function() {
var rc = $(this).html();
if (queryParameters['page'] < rc) {
queryParameters['page']++;
console.log(rc);
var stateObj = queryParameters['page'];
let cagh = $('#cagorwrap').height() + 344.6 - 75;
$("#cagorwrap").height(cagh);
history.pushState(null, null, "categor.php?artemis=cat&&page="+stateObj);
var url = "modules/paginate.php?artemis=cats&&page="+stateObj;
$("#obtainer").load(url, function () {
$("#cagorwrap").append($(this).html());
}); //#obtainer is a hidden div that receives the data at first before it is appended to #cagorwrap
} else{
//unbind scroll here
}
});
}
});
well if all else fails and you absolutely need a solution, you can add a
counter=1; on the start
and only fire the request function in the case below
counter++;
if (counter%2==0){//fire request}
It's not clean, but if you're loosing too much time with this and want to return to the problem later on...

simple chat using jQuery and PHP

I'm not so good at English but I will give it a try, feel free to edit and improve my post!
I'm trying to create a little chat, now I do not want to reload when there's no new data. It will receive the data from update.php, this works correctly.
I'm trying to do a little check (sample to show what I want to accomplish):
This is standard:
var ok = update.php
load ok(4000s);
What I am trying to accomplish here is:
var ok = update.php
function timer{
var new = update.php
if(new != ok){
ok = new;
},4000};
Of course this is fake code, it would never run, but it's the easiest way to explain what I mean.
$(document).ready(function() {
$("#chatbox").html('').load("update.php");
var refreshId = setInterval(function() {
var xx = $("#chatbox").html('').load("update.php");
$('#holder').load('update.php');
if( xx != "#holder"){
$("#chatbox").html('').load('update.php');
// $("#chatbox").html('').load('update.php')
$("#chatbox").scrollTop($("#chatbox")[0].scrollHeight);
}else{
alert)('nooope');
}
}, 4000);
$.ajaxSetup({ cache: false });
});
I tried everything, still getting nope.
(chatbox is a div, where de data gets loaded into.)
(holder is the same concept, only this one is hided trough css, so that the user won't notice.)

Re-enabling the submit button after a timeout

The submit_pdf button saves up the information into the database and to avoid multiple clicks, i initially had disabled the submit button after one click, however now i would like to re enable the button after a timeout of 10 seconds. The part till where the submit button gets disabled is working fine, but if i try to add a delay of 10 seconds, it doesn't seem to work.It would be really helpful if you could help me out with this.
echo ' <script language="JavaScript" type="text/javascript">
//<![CDATA[
window.open(\'./index_pdf.php?'.$query_string.'\',\'Warehouse_ST\',\'location=no,menubar=no,resizable=yes,scrollbars=yes,status=yes,toolbar=no\');
id_form.submit_pdf.disabled=true;
window.alert("Data is stored in the database, Please do no click on Submit again without changing any information");
window.addEvent(\'domready''\',function()
{
var subber = $_REQUEST["submit_pdf"];
subber.addEvent( \'click' ,function() '
{
subber.set( \'value','Submitting...''\' ).disabled = true;
(function() { subber.disabled = false; subber.set(\'value','submit_pdf'\'); }).delay(10000); // how much time? 10 seconds
});
});
//]]>
</script>';
try using setTimeout()
define a function to enable the button, and then set a setTimeout():
function enableButton(){
$('#myButton').attr("disabled", false);
}
setTimeout(enableButton, 10000);
make sure to put the function name without quotes and without the "()"
I recommend to write JS code (aleation 's code is correct) and this PHP code.
PHP (store the time in a session var):
session_start(); //At the beginning of the PHP file
define("TIMEOUT", 10); //10 sec
//Check timeout
if (isset($_SESSION['expire'])) {
if ($_SESSION['expire']-time()>TIMEOUT) {
unset($_SESSION['expire']);
}
}
//Allow to do submit after 10 sec
if (!isset($_SESSION['expire'])) {
$_SESSION['expire']=time();
//Your submit code
}
This is because user can manipulate JavaScript and HTTP messages, but he/she can't manipulate php code.

auto logout idle timeout using jquery php

I searched and find some examples to set idle timeout using jquery.
1 - Idle Timeout By Eric Hynds DEMO
2 - Idle Timer By paulirish
3 - Fire Event When User is Idle / DEMO HERE
4 - detect user is active or idle on web page
5 - Comet Long Polling with PHP and jQuery
6 - detacting idle timeout javascript
... And several other similar examples
Between these examples number 1 is better for i need because i need to auto logout user with any confirm alert after X minutes (logout.php or any url). but this method Not suitable for server. problem is : this jquery code send ping to any url : keepAlive.php in loop/pooling for request OK text . see firebug screen :
how to fix this ?
So, other examples only printed Idle/No Idle and not work with alert confirm and auto logout ( logout.php or any url ) now really better way to choose idle timeout using jquery/Php ?
Thanks
I use a meta refresh element in the head section to auto-direct users to the logout page after X number of seconds. Below will automatically send a user to the logout page after 20 minutes of staying on the same page:
<meta http-equiv="refresh" content = "1200; url=http://www.site.com/user/logout">
This works, is (mostly) supported cross-browser, does not rely on JavaScript being enabled and is pretty easy to implement.
If your site has users that stay on the same page for extended periods of time (with interaction taking place through JS, for instance), this solution will not work for you. It also does not allow any JS code to be run before redirection takes place.
Here is my approach that I applied to build a simple auto-logout feature with JavaScript and jQuery. This script was constructed for use with webpages that will automatically go to the logout page when mouse movement is not detected within 25 minutes.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
var idleMax = 25; // Logout after 25 minutes of IDLE
var idleTime = 0;
var idleInterval = setInterval("timerIncrement()", 60000); // 1 minute interval
$( "body" ).mousemove(function( event ) {
idleTime = 0; // reset to zero
});
// count minutes
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > idleMax) {
window.location="LogOut.php";
}
}
</script>
<script>
var idleMax = 5; (5 min)
var idleTime = 0;
(function ($) {
$(document).ready(function () {
$('*').bind('mousemove keydown scroll', function () {
idleTime = 0;
var idleInterval = setInterval("timerIncrement()", 60000);
});
$("body").trigger("mousemove");
});
}) (jQuery)
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > idleMax) {
window.location="Your LOGOUT or Riderct page url here";
}
}
</script>
Easy and simle
var autoLogoutTimer;
resetTimer();
$(document).on('mouseover mousedown touchstart click keydown mousewheel DDMouseScroll wheel scroll',document,function(e){
// console.log(e.type); // Uncomment this line to check which event is occured
resetTimer();
});
// resetTimer is used to reset logout (redirect to logout) time
function resetTimer(){
clearTimeout(autoLogoutTimer)
autoLogoutTimer = setTimeout(idleLogout,5000) // 1000 = 1 second
}
// idleLogout is used to Actual navigate to logout
function idleLogout(){
window.location.href = ''; // Here goes to your logout url
}

Ajax div refresh (without fading in and out)

So i have looked around and most of the code for this looks needlessly beefy. I am looking for lightweight ajax code that refreshes a div with an action like:
load('boo.php')
And I need it to load first on the page opening (ie no delay) then every x seconds refresh (without fade) so you cannot notice a change unless my Database rows have updated but I can do the db bit.
I think i would need something like:
onreadystatechange
to load when the page loads? Eh im not too sure on this :( any help would be much appreciated!
Thanks!
I totally recommend using some library for cross-browser support and tested code, e.g. jQuery.
With jQuery, it's as simple as
$.get('boo.php', function(data){$('#divId').html(data);});
You can wrap this in a function and call it on document ready, then use setInterval as suggested by #M1K1O
Update
To run the code when the DOM is loaded, the jQuery API documentation for ready states that
All three of the following syntaxes are equivalent:
$(document).ready(handler)
$().ready(handler) (this is not
recommended)
$(handler)
Here is a complete example:
function refreshDiv()
{
$.get('boo.php', function(data){$('#divId').html(data);});
}
$(function()
{
refreshDiv();
setInterval(refreshDiv, x * 1000); // x is the number of seconds
});
var counter = 0;
var timer = null;
function progressBar(){
if (timer) {
clearTimeout(timer);
timer = null;
return;
}
timer = window.setInterval(function(){
load('boo.php');
}, 10);
}
window.onload = function() {
progressBar();
};
Try this
Do you use some libries like Jquery ?
Here is some code on jquery for.
function update()
{
$.get(<URI>,{check:1},function(data){
$('#div').html(data);
});
setTimeout('update()',1500);
}
$(function(){
update();
});

Categories