javascript not working - php

I have following javascript code. Its a timer code. Timer stops if quiz is 3 for 3 seconds and starts after 3 seconds for 20 seconds. But this code is not working for if quiz is anything else than 3. Can anyone help me with this?
<script type="text/javascript">
var days = 0
var hours = 0
var minutes = 0
var seconds = 20
var delay_countdown = <?php echo ($quiz == 3) || 0 ; ?>;
function setCount ()
{
document.getElementById("remain").innerHTML = seconds+" seconds";
SD=window.setTimeout( "setCount()", 1000 );
if (delay_countdown) {
return
}
seconds--;
if (seconds < 0){
minutes--;
seconds = 59
}
if (minutes < 0){
hours--;
minutes = 59
}
if (hours < 0){
days--;
hours = 23
}
}
</script>

Your script works for me if $quiz is anything else than 3(if it's 3 delay_countdown will be true and you return the function on the 4th line).
Supply a different delay-time when delay_countdown is true:
SD=window.setTimeout( setCount, (delay_countdown)?3000:1000 );
and set delay_countdown to false before leaving the function:
if (delay_countdown) {
delay_countdown=false;
return;
}

Related

Need help adding "days" to this jquery countdown timer [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I currently have a countdown timer that shows hours, mins, seconds. But now I would like to add "days" to it. Can you please show me how you would do that?
Here's the code. I left out the php db query as it's not important.
function Timer(container, timeLeft) {
// get hour, minute and second element using jQuery selector
var hoursContainer = $(container).find('.hour');
var minsContainer = $(container).find('.min');
var secsContainer = $(container).find('.sec');
// hold time left
var currentTimeLeft = timeLeft;
// 1 second = 1000 ms
var secondsForTimer = 1000;
// hold ID value return by setInterval()
var timerInterval;
// call setInteval() only when timeLeft is greater than 0
if (currentTimeLeft == 0) {
return;
} else {
//Call setInterval()function and store ID value to timerInterval.
timerInterval = setInterval(countdown, secondsForTimer);
}
//function being passed to setInterval()
function countdown() {
currentTimeLeft = parseInt(currentTimeLeft - secondsForTimer);
if (currentTimeLeft == 0) {
//stop calling countdown function by calling clearInterval()
clearInterval(timerInterval);
return;
} else {
//calculate hours left
var wholeSeconds = parseInt(currentTimeLeft / 1000,10);
var wholeMinutes = parseInt(currentTimeLeft / 60000,10);
var wholeHours = parseInt(wholeMinutes / 60,10);
//calculate minutes left
var minutes = parseInt(wholeMinutes % 60,10);
//calculate seconds left
var seconds = parseInt(wholeSeconds % 60,10);
//prefix 0 to hour, min and second counter
$(hoursContainer).text((wholeHours < 10 ? "0" : "") + wholeHours + (wholeHours <=0 ? " hr" : " hrs"));
$(minsContainer).text((minutes < 10 ? "0" : "") + minutes + (minutes <=0 ? " min" : " mins"));
$(secsContainer).text((seconds < 10 ? "0" : "") + seconds + (seconds <=0 ? " sec" : " secs"));
}
}
}
<?php
// db query here to get the expiry time from the database
foreach($results as $k => $row) {
$expiry_date = $row['expiry_date'];
$timeLeft = (strtotime($expiry_date) - time()) * 1000;
$counterName = "counter_$k";
?>
<div class="counter <?php echo $counterName; ?>">
<span class="hour">00</span>
<span class="min">00</span>
<span class="sec">00</span>
</div>
<script>
// initiate new timer
var timer = new Timer($('.<?php echo $counterName; ?>'), <?php echo $timeLeft; ?>);
</script>
<?php
}
?>
Try this
function Timer(container, timeLeft) {
// get hour, minute and second element using jQuery selector
var daysContainer = $(container).find('.day');
var hoursContainer = $(container).find('.hour');
var minsContainer = $(container).find('.min');
var secsContainer = $(container).find('.sec');
// hold time left
var currentTimeLeft = timeLeft;
// 1 second = 1000 ms
var secondsForTimer = 1000;
// hold ID value return by setInterval()
var timerInterval;
// call setInteval() only when timeLeft is greater than 0
if (currentTimeLeft == 0) {
return;
} else {
//Call setInterval()function and store ID value to timerInterval.
timerInterval = setInterval(countdown, secondsForTimer);
}
//function being passed to setInterval()
function countdown() {
currentTimeLeft = parseInt(currentTimeLeft - secondsForTimer);
if (currentTimeLeft == 0) {
//stop calling countdown function by calling clearInterval()
clearInterval(timerInterval);
return;
} else {
//calculate hours left
var wholeSeconds = parseInt(currentTimeLeft / 1000,10);
var wholeMinutes = parseInt(currentTimeLeft / 60000,10);
var wholeHours = parseInt(wholeMinutes / 60,10);
var wholeDays = parseInt(wholeHours / 24,10);
//calculate hours left
var hours = parseInt(wholeHours % 24,10);
//calculate minutes left
var minutes = parseInt(wholeMinutes % 60,10);
//calculate seconds left
var seconds = parseInt(wholeSeconds % 60,10);
//prefix 0 to hour, min and second counter
$(daysContainer).text((wholeDays < 10 ? "0" : "") + wholeDays + (wholeDays <=0 ? " day" : " days"));
$(hoursContainer).text((hours < 10 ? "0" : "") + hours + (hours <=0 ? " hr" : " hrs"));
$(minsContainer).text((minutes < 10 ? "0" : "") + minutes + (minutes <=0 ? " min" : " mins"));
$(secsContainer).text((seconds < 10 ? "0" : "") + seconds + (seconds <=0 ? " sec" : " secs"));
}
}
}
Add days container on your loop
<div class="counter <?php echo $counterName; ?>">
<span class="day">00</span>
<span class="hour">00</span>
<span class="min">00</span>
<span class="sec">00</span>
</div>
Fiddle: https://jsfiddle.net/otezz/68d9yb6v/1/

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();

Cronjob but for jQuery/Javascript

I'm trying to develop a web application that mainly uses PHP but i'm using jQuery/Javascript to grab people's Tweets from their URL: http://twitter.com/status/user_timeline/joebloggs.json?count=1&callback=?
The thing is want to run a PHP cron job to grab latest tweets from people who have signed up for my application. But i dont know how to do this with javascript?
Is this possible?
EDIT:
This is the javascript code, can i do this in PHP so i can use a Cron Job?
$(document).ready( function() {
var url = "http://twitter.com/status/user_timeline/joebloggs.json?count=1&callback=?";
$.getJSON(url,
function(data){
$.each(data, function(i, item) {
$("#twitter-posts").append("<p>" + item.text.linkify() + " <span class='created_at'>" + relative_time(item.created_at) + " via " + item.source + "</span></p>");
});
});
});
String.prototype.linkify = function() {
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
}
function twitter_callback ()
{
return true;
}
The javascript method setInterval allows you to pass a method and a number of milliseconds. The method you provide will be executed every number of milliseconds you provided. So if you wanted to grab the latest tweets every 30 seconds, you would call something like this:
setInterval(updateTweets,30000);
This would call the method updateTweets every thirty seconds, where you could use ajax to load up the latest tweets.
For more information on setInterval, you can check out: http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
The best solution is to re-implement your functionality in PHP:
<?
$url = "http://twitter.com/status/user_timeline/joebloggs.json?count=1&callback=?";
$responseJsonString = file_get_contents($url);
$responseArray = json_decode($responseJsonString, $array=true);
// uncomment this to see what's in the response array:
// print_r($responseArray);
// Now, you can do as you like with $responseArray
And then execute the PHP script via crontab.

php ajax auto logout with timer

<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;
}

Categories