javascript timer not counting down when retrieving time from db - php

I am trying to follow a jsfiddle example to create a time in javascript:
http://jsfiddle.net/g3rRJ/
Now obviously the timer in the jsfiddle works fine. But the issue I have is that the time which the timer starts from comes for a mysqli/php variable where it retrieves the time from the db.
So except for:
<span id="countdown">01:30:10</span>
I have to have it as:
echo "<p><span id='countdown'>" . $dbSessionDuration . "</span></p>";
AND
except for:
var time = "01:30:10",
I have to have it as:
var time = <?php echo json_encode($dbSessionDuration); ?>,
Now I am getting no errors but what is happening is that the timer is not doing a count down. My question is why is it not counting down? An example of the time from the variable could be 01:00:00.
Below is the code for the function:
echo "<p><span id='countdown'>" . $dbSessionDuration . "</span></p>";
...
<script type="text/javascript">
(function(){
$(document).ready(function() {
var time = <?php echo json_encode($dbSessionDuration); ?>,
parts = time.split(':'),
hours = +parts[0],
minutes = +parts[1],
seconds = +parts[2],
span = $('#countdown');
function correctNum(num) {
return (num<10)? ("0"+num):num;
}
var timer = setInterval(function(){
seconds--;
if(seconds == -1) {
seconds = 59;
minutes--;
if(minutes == -1) {
minutes = 59;
hours--;
if(hours==-1) {
alert("timer finished");
clearInterval(timer);
return;
}
}
}
span.text(correctNum(hours) + ":" + correctNum(minutes) + ":" + correctNum(seconds));
}, 1000);
});
});
</script>

Change this:
});
});
</script>
to this:
});
})(); // ← note the extra parentheses
</script>
so that you actually call your anonymous function. (Alternatively, you can simply remove its (function(){ and }); entirely. There's no reason for this code to be in a function at all.)

I don't know if this was a mistype but I was able to run this code by adding $, $(function(){, at the first part of your anonymous function. I'm assuming your value from the db comes in as hours:mins:secs. I'm not sure why Fiddler ran but I had to add that to get it to work in my environment.

Related

How to display realtime change in server date and time every 1 Sec in php?

I wrote this php code to show server date and time but I'd like to display realtime change in server date and time every 1 Sec
<p><?php echo "Server Time " . date("Y-m-d h:i:s"); ?> (GMT) UTC +0 UK/London</p>
Pls help me, thank you
You will need to use Javascript, something like this:
<body>
<p id="time"></p>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
var timestamp = '<?=time();?>';
function updateTime(){
$('#time').html(Date(timestamp));
timestamp++;
}
$(function(){
setInterval(updateTime, 1000);
});
</script>
if you still need a real time clock that uses your server clock you could try this. im using twig {{now|date('Y/m/d H:i:s')}}. but you could also use php's <?php echo date('Y/m/d H:i:s');?>. its basically using localStorage to store the server date on localstorage and setSeconds updates the localstorage every 1 second , while the now variable loads the localstorage date and converts it to js date format. I then use the {{now|date('Y/m/d H:i:s')}} inside the date element for fallback in case localstorage is not enabled.
try {
localStorage.setItem('today', new Date("{{now|date('Y/m/d H:i:s')}}");
setInterval(function clock() {
var month = [
"Jan", "Feb", "Marh", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Octr", "Nov", "Dec"
];
var now = new Date(localStorage.getItem('today'));
now.setSeconds(now.getSeconds() + 1);
localStorage.setItem('today', now);
var G = format(now.getHours() % 12 || 12);
var i = format(now.getMinutes());
var s = format(now.getSeconds());
var M = month[now.getMonth()];
var d = format(now.getDate());
var Y = now.getFullYear();
function format(data) {
return (data < 10 ? data = "0" + data : data);
}
$("#date").html(M + ". " + d + ", " + Y + " " + G + ":" + i + ":" + s);
return clock;
}(), 1000);
} catch(e) {
console.log(e);
}
you can get server time when page loaded and use javascript function to update time locally persecond.
HTML PAGE
<script> var JS_BASE_URL = 'http://YOURSERVER/';</script>
<script src="assets/js/jquery-3.4.1.min.js" type="text/javascript"></script>
<script src="clock.js" type="text/javascript"></script>
</head>
<body>
Server Time <span id="server_time">00:00:00</span>
</body>
clock.js
var url = JS_BASE_URL+'/script.php';
var _h = 0;
var _m = 0;
var _s = 0;
$.ajax({
url: url,
type: 'GET',
dataType: 'JSON',
success: function(res) {
var timer = setInterval(serverTime,1000);
function serverTime(){
h = parseInt(res.hour)+_h;
m = parseInt(res.minute)+_m;
s = parseInt(res.second)+_s;
if (s>59){
s=s-60;
_s=_s-60;
}
if(s==59){
_m++;
}
if (m>59){
m=m-60;
_m=_m-60;
}
if(m==59&&s==59){
_h++;
}
_s++;
$('#server_time').html(append_zero(h)+':'+append_zero(m)+':'+append_zero(s)); }
function append_zero(n){
if(n<10){
return '0'+n;
}
else
return n;
}
}
});
script.php
<?php
$data = array('fulldate'=>date('d-m-Y H:i:s'),
'date'=>date('d'),
'month'=>date('m'),
'year'=>date('Y'),
'hour'=>date('H'),
'minute'=>date('i'),
'second'=>date('s')
);
echo json_encode($data);
?>
check on github: https://github.com/mdanielk/server_time
To display changing clock showing server time by using Ajax. Create two files for this one is the file sending request and receiving data with Ajax.
server-clock.php
develop a script where by clicking a button we can send a request to server to get the data. In the body of this file we have a button.
<input type=button value=
'Get Server Time' onclick="timer_function();">
To this script we will add a timer to recursively call the same Ajax function in every second. This will get data from every second so we can display a changing clock showing server time.
function timer_function(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('AjaxFunction();',refresh)
}
Timer function: timer_function()
On click of this button it trigger a function which uses a timer setTimeout. Inside this timer function it can change the refresh rate which is in milliseconds. Within this function we call our main Ajax function AjaxFunction()
function timer_function(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('AjaxFunction();',refresh)
}
At the end of AjaxFunction() call again timer_function() to make it recursive.
tt=timer_function();
In the main AjaxFunction() send request to clock.php file and get the server time. This data is displayed using a div layer.
if(httpxml.readyState==4)
{
document.getElementById("msg").innerHTML=httpxml.responseText;
document.getElementById("msg").style.background='#f1f1f1';
}
The second file is the simple PHP file with one line of code giving current date and time of server. clock.php
<?Php
echo date("d/m/y : H:i:s", time());
?>
download the files here

Ajax with jquery to set time interval

I'm working on a notification message i want to load new message from a page call check_new-reply.php in every 10 second using Ajax and Jquery but my code is not showing anything i don't know what the error is please can someone help me out?
<script>
$(document).ready(function(){
$(function(){
var timer = 10;
var test = "";
function inTime(){
setTimeOut(inTime, 1000);
$("#timer-u").html("Time refreshing"+timer);
if(timer == 8){
$("#message-u").html("Loading....");
$.POST("check_new_reply.php",{testing:test}, function(data){
$("#message-u").html(data);
})
timer = 11;
clearTimeout(inTime);
}
timer--;
}
inTime();
});
});
</script>
Here is PHP
<?php include($root . '_inc/Initialization.php');?>
<?php require_once("_inc/dbcontroller.php"); $db_handle = new DBController();?>
<?php
$users = $_SESSION['username'];
$newquery = "SELECT * FROM blog_post
INNER JOIN replys
ON blog_post.UserName = '$users'
WHERE replys.read = 0
ORDER BY rtime";
$newhisory = mysql_query($newquery);
while($newrow = mysql_fetch_array($newhisory)){
echo '<div class="fnot">'.htmlentities($newrow['blog_title']).'';
echo '<span class="ttcredit"><font color="darkgreen">94</font> </span> <a class="reqttag reqttag2" href="#">No</a> ';
echo '</div>';
echo '<input type="hidden" id="unr" name="unr" value="'.$newrow['BID'].'"/>';
}
?>
If you just want to call it every 10 seconds, use 10000 milliseconds in the setTimeOut . Also, it is best to call again the function only when the previous Ajax call is done:
$(document).ready(function(){
$(function(){
var test = "";
function inTime(){
$.POST("check_new_reply.php",{testing:test}, function(data){
$("#message-u").html(data);
setTimeout(inTime, 10000);
});
}
inTime();
});
});
To call any function with some intervals you will have to use
<script>
$(document).ready(function(){
window.setInterval(function(){
myAjaxCall();
}, 10000);
});
function myAjaxCall() {
alert("Hi");
$("#message-u").html("Loading....");
$.POST("check_new_reply.php",{testing:test}, function(data){
$("#message-u").html(data);
});
}
</script>
window.setInterval will call your function on every 3 seconds with above code, and will generate an alert message,
what you have to do is set your ajax code in a function and use above method, change 3000 to 10000 and your ajax call will defiantly work with every 10 seconds,
This is the code which will call our javascript function on every 10 seconds,
just copy it and check it, you will get an idea, also i have included the jquery as we have discussed.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
</body>
<script>
$(document).ready(function(){
window.setInterval(function(){
myAjaxCall();
}, 3000);
});
function myAjaxCall() {
alert("Call your Ajax here");
$("#message-u").html("Loading....");
$.POST("check_new_reply.php",{testing:test}, function(data){
$("#message-u").html(data);
});
}
</script>

javascript countdown update db and refresh

can someone please help me with js/ajax countdown i want a countdown timer to 10 sec then update the database and refresh the page once it hits to 0.
i'm not really good with javascript/ajax, here is what i got so far:
var ss = 10;
function countdown() {
ss = ss-1;
if (ss<0) {
var url='update.php?countdown='+countdown;
}
else {
document.getElementById("countdown").innerHTML=ss;
window.setTimeout("countdown()", 1000);
}
}
<span id="countdown" style="color:green;">10</span>
and update.php file, witch works fine:
if (isset($_REQUEST['countdown'])) {
mysql_query("INSERT INTO num (id, ad, active)
VALUES ('1', 'Test',1)") or die(mysql_error());
}
and also this is what i found http://pastebin.com/Qwz3Zqtt , works fine but i don't know how to put them together.
any helps would be appreciated.
Thanks
You're going to want to learn basic ajax to process the database request. jQuery has a very easy to use implementation.
The basic code could be something like:
<script>
function updateTimer(seconds){
var countdown = document.getElementById('countdown');
countdown.innerHTML = "Please wait " + seconds + " seconds.";
}
var timer = function() {
var seconds = 10;
var interval = setInterval(function(){
if (seconds <= 0){
countdown.innerHTML = "Finished.. Updating Database";
// AJAX request here
clearInterval(interval);
}else{
updateTimer(seconds);
--seconds;
}
}, 1000);
updateTimer(seconds);
--seconds;
}
document.getElementById('start').addEventListener('click', timer);
</script>
<div id="countdown"></div>
<button id="start">Click Me</button>
Here's a fiddle
Use jQuery ajax
Simplest example:
if (ss<0) {
$.ajax('update.php?countdown='+countdown);
}

JavaScript Countdown (counting up) milliseconds too quick, wont load next page?

javascript too fast when i set setInterval(function() down (or up i guess, speed wise) to 100 or 500 and wont load mypage.php as it doesn't have time i think? don't want to slow counter down either. so is there a php equivalent that can? (with the little number display like this, see jsfiddle) or is there a better javascript counter ? would prefer php, any ideas?
Thanks heaps, any help would be great.
Changed the page link to # as it will freeze things otherwise
http://jsfiddle.net/aEXgB/2/ Also added exit;but didn't help.
<html>
<head>
<script type="text/javascript">
function countdown() {
var i = document.getElementById('counter');
if (parseInt(i.innerHTML)>=3000) {
location.href = 'mypage.php';
exit;
}
i.innerHTML = parseInt(i.innerHTML)+1;
}
setInterval(function(){ countdown(); },.75);
</script>
</head>
<body>
<div style="margin-left:20px; float:left;"><p>Countdown:<font color="#33CC00"> <span id="counter">10 </span></font></p></div>
</body>
</html>
replace
setInterval(function(){ countdown(); },.75);
with
var t = setInterval(function(){ countdown(); },.75);
then just before the exit in the function, add;
clearInterval(t);
First, I don't understand why it's called a countdown when you count UP.
Second, I think it's better to update the counter and THEN check the value. That way you don't have an extra call to the coundown function.
Third, clear the interval before changing location because the interval is probably getting fired again too quickly.
Fourth, this won't actually work in jsfiddle because of how jsfiddle uses iframes :)
var interval = setInterval(function(){ countdown(); },.75);
function countdown() {
var i = document.getElementById('counter');
i.innerHTML = parseInt(i.innerHTML)+1;
if (parseInt(i.innerHTML)>=3000) {
clearInterval(interval);
window.location.href = "mypage.php";
}
}
JS:
var sec = 0;
var interval = 750; // milliseconds
var stop = 5; // seconds
function pad ( val ) { return val > 9 ? val : "0" + val; }
setInterval( function(){
if(document.getElementById("seconds").innerHTML < stop) {
document.getElementById("seconds").innerHTML=pad(++sec%60);
} else {
location.href = 'http://google.nl'
}
}, interval);
Html:
<div id="seconds></div>
Fiddle:
http://jsfiddle.net/5tM3A/5/

Call a function outside of a dynamic jquery slider

I am dynamically creating my sliders and in the "Slide" event and "Stop" event I would like to call a function that is defined in the non dynamic content. I can get the functions to work if I create them each time with the slider, but that seems like a lot of redundant code?
Non Dynamic function
$(document).ready(function() {
var converSecondsToMinutes;
convertSecondsToMinutes = function(secondsEntered){
var secondsEntered = secondsEntered;
var time = parseInt(secondsEntered,10);
time = time < 0 ? 0 : time;
var minutes = Math.floor(time / 60);
var seconds = time % 60;
minutes = minutes < 9 ? "0"+minutes : minutes;
seconds = seconds < 9 ? "0"+seconds : seconds;
var newTime = minutes+":"+seconds
console.log(newTime);
return newTime
}
});
Dynamic jQuery slider
<?php
query...
result...
for(...){
?>
<Script>
$( "#slider"+<?php echo $id; ?> ).slider({
animate: true ,
value: 0,
min: 0,
//dynamic grab this
max: <?php echo $playtime_seconds; ?>,
step: 0.01,
start: function( event, ui ) {
....
},
slide: function( event, ui ) {
audio = ....
audio.currentTime = ui.value;
progress_seconds = parseFloat(audio.currentTime.toFixed(2));
progress_seconds = $(function(){convertSecondsToMinutes(progress_seconds);});
$('#progress_seconds'+<?php echo $id; ?>).html(progress_seconds);
},
stop: function( event, ui ) {
....
}
}
});
});
}
I cut and paste the parts of the code that were important to the question.
This is the line that is not working: $('#progress_seconds'+).html(progress_seconds);
You edited just after I commented, so my comment no longer made sense, the $(function(){ part of your code is not necessary, try just using:
progress_seconds = converSecondsToMinutes(progress_seconds);
And spelling errors in code are a real issue with me, conver has a t at the end.
There is also no need to wrap your function in $(document).ready(), declare it like this:
function convertSecondsToMinutes(secondsEntered)
{
var time = ...
...
}

Categories