So i have a few sites with a timer on when it gets to 0 it does something but my next project is a market place website were users can bid on items im getting a bit stuck with the timer on my current projects the user stays on the page the timer goes to 0 then they get what they wanted of course on the auction site if users are not viewing the page ( sat ion the page ) my timer wont go down. And im guessing a cron job every second will kill my server. I understand the users adds the item and the date and time is added then i can set the end time and add that but havn't any ideas were to go from there here is my time
<?php
$random_word = preg_replace('/([ ])/e', 'chr(rand(97,122))', ' ');
$timer = '26';
?>
<script type="text/javascript">
// Check if the page has loaded completely
$(document).ready( function() {
setTimeout( function() {
$('#some_id').load('http://mydomainname.com/parser.php');
}, 23000);
});
</script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
setTimeout("location.href='surf.php?id=<?php echo $random_word ; ?>'", 26000);
});
// ]]></script>
Related
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.
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
}
i created a banner that i want it to appear after 4 minutes.
I use modalbox to show the banner.
i need something like that
If customers_session_time > 4 minutes then show me the banner
But if i store customers_session_time to the database and write some code on PHP, then the user will have to refresh the page to see the banner.
If i use javascript's setTimeout() the thy timeout period will be refreshed every time the user refreshes the page...
Is there another way?
Not a very complete code, but you may catch an idea
<?php
session_start();
if( empty($_SESSION['time_session_started']) ){
$_SESSION['time_session_started'] = time();
}
$timeout = $_SESSION['time_session_started']+4*60 - time();
if( $timeout<0 ){
$timeout = 0;
}
?>
<script language="JavaScript">
<?php if( $timeout ){ ?>
setTimeout(function (){
showBanner();
},<?php echo $timeout*1000; ?>);
<?php }else{ ?>
showBanner();
<?php }
</script>
Remember the timestamp when user requests Your site in session.
Each time the user enters the site You will check if he is here for the first time or when did he came the latest. Then compute time spent already on the site in the session.
var timeSpentOnSites = (1000*60*4) - <?= $_SESSION['TIME_SPENT_ALREADY'] ?>;
$(document).ready(function(){
setTimeout(function(){
$('#banner').show();
},timeSpentOnSites < 0 ? 0 : timeSpentOnSites);
});
You cannot access any sessions in JavaScript as it is client sided.
What you can do is that AFTER the DOM has been sucessfully loaded you can use the setTimeout(); method and show the banner after 4 minutes.
$(document).ready(function(){
setTimeout(function(){
$('#banner').show();
},(1000*60*4));
});
EDIT: the question was edited after I posted the answer. The answer responds to the first question markup.
I am looking at writing a cookie that will be updated everytime the 'news scroller' moves to the next image/news item. when a user returns to the page it will automatically then start the scroller from the next news item.. helping to ensure our users get to see all the items.
i am using the 'anything scroller' by chris coyier et al, with php to pull in the news data.
each element has a unique id and are in numerical order so my cookie needs to retrieve the latest value and then +1 . the scroller allows for triggers to specific items.. but i can't seem to get the cookie to update on each, moreover it loads once the maximum id of those rendered in html...
is this even practical? assuming a maximum of 10 news items, would it slow the website down.
edit this is the could trying to get some output to the browser / console... but nothing.
<script>
// Set up Sliders
// **************
$(function(){
$('#slider').anythingSlider({
theme : 'minimalist-round',
easing : 'swing',
infiniteSlides : true,
delay : 8000, // How long between slideshow transitions in AutoPlay mode (in milliseconds)
resumeDelay : 8000, // Resume slideshow after user interaction, only if autoplayLocked is true (in milliseconds).
animationTime : 1, // How long the slideshow transition takes (in milliseconds)
autoPlayLocked : true, // If true, user changing slides will not stop the slideshow
})
$('#slider').bind('slide_complete', function(event, slider){
console.debug( 'You are on page ' + slider.currentPage );
// Do something else
})
});
</script>
solution: using local storage this works
<script type="text/javascript">
var ls = null, // local storage
sp = 1; // starting page
if ('localStorage' in window && window['localStorage'] !== null) {
ls = window.localStorage;
sp = ls.getItem('anythingSlider') || 1;
}
</script>
and
<script>
$('#slider').anythingSlider({
startPanel: sp,
// Callback when slide completes - no event variable!
onSlideComplete: function(slider) {
if (ls) {
ls.setItem('anythingSlider', (slider.currentPage+1));
$('.storage').val(slider.currentPage);
}
}
</script>
Let me post the code first.
function alertCallback<?=$position_info['id']?>()
{
var id = <?=$position_info['id']?>;
var itemname= '<?=$na?>';
<?PHP if($position_info['name'] == $wposition){ ?>
var reward = '<?= $itmname ?>';
$('#selected_item').html(''+itemname+reward);
<?PHP item_add($_SESSION['userid'],$itmid,1); } else { ?>
var noreward = 'You Found Nothing!';
$('#selected_item').html(''+itemname+noreward);
<?PHP } ?>
}
The above is working to an extent. The page is a image map where if you click on the right spot then you get an item. It is currently working where if you click on the right spot you get the item. Or get told you found nothing.
The problem I have is that the page reloads to set new positions
<script type="text/javascript">
//one seconds=1000 micro seconds
setInterval(function() {
$('#load').load('itemclick_ajax.php');
},60000);
</script>
but another item is won as long as the page is displayed. Any ideas on how to stop this occuring. If i keep the browser showing the page then im running up to thousands of items won.
Are you trying to stop the page reload?
Try adding "return false;" at the end of your Javascript function.