javascript countdown update db and refresh - php

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

Related

Implementing Timer in PHP and Sleep function

I am creating an PHP application in which i want to set a timer of 15 minutes for a particular section of test. If the student doesn't complete the section in 15 minutes the scores are saved and the student is navigated to the next section.
So i want to create a timer and want to display the current time left. But i don't know how to implement it and also if we use sleep() function that will it interrupt the working of other functions as well.
You can't use PHP for this. If you do, then it will simply freeze the page on page load for 15 seconds and then tell the student time has expired.
So, you should write it in JavaScipt like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
currentMinute = 0;
myTimer = setInterval(function () {
if (currentMinute > 15) {
clearInterval(myTimer);
//send post data that the user's time is up
return;
}
$.post("sendData.php", {
"timeIsUp" : true
}, function (data) {
console.log("done sending time has expired to server");
});
currentMinute++;
}, 60 * 1000);
</script>
jQuery will help you on this...
Use below function for timer
var hours1=0, minutes1=0, seconds1=0;
function calculate() {
setTimeout(calculate, 1000);
if((hours==0)&&(minutes==0)&&(seconds==0)){$('#submit-btn').trigger('click');} // HERE YOU CAN SWITCH TO NEXT QUESTION
h1 = makeTwoDigit(hours); m1 = makeTwoDigit(minutes); s1 = makeTwoDigit(seconds);
h2 = makeTwoDigit(hours1); m2 = makeTwoDigit(minutes1); s2 = makeTwoDigit(seconds1);
$('title').html(h1+':'+m1+':'+s1);
$('#time-taken').val(h2+':'+m2+':'+s2);
$('#minutes').html(m1);
$('#seconds').html(s1);
seconds--;
if (seconds < 0) {
seconds = 59; minutes--;
if (minutes < 0) {
hours--;
minutes = 59;
}
}
seconds1++;
if (seconds1 > 59) {
seconds1 = 00; minutes1++;
if (minutes1 >59) {
hours1++;
minutes1 = 00;
}
}
}
function makeTwoDigit(num) {
if (num < 10) { return "0" + num;} return num;
}
Thanks

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

PHP AJAX Comet with MySQL select record

I would like to implement comet with records fetch from PHP
My PHP will do the following.. at a page call getlog.php
$sql = "select log_description,log_time from log ORDER by log_time DESC";
$result=mysql_query($sql);
if($result == false)
{ die("unable to fetch records."); }
while ($row = mysql_fetch_assoc($result)) {
$result_output[] = $row;
}
$counter = 1;
foreach($result_output as $row)
{
echo $counter . ". " $row[log_description];
$counter++;
}
If there is new log, I would want to echo it out in viewlog.php
So it would appear like this in viewlog.php
1. Customer 1 logged in at 12:05.
maybe 5 minutes later
1. Customer 2 logged in at 12:10
2. Customer 1 logged in at 12:05
It maintain a maximum of like lets say 15 records.
The data is fetch from PHP, I read the way to do it is something call "comet" but I just want a simple database fetch which auto refresh e.g every 10 seconds to see if there is new record added to the database and append it to the div.
Is there a easy way to achieve this using AJAX and PHP and not using comet.
Thanks for all the help, greatly appreciate !
Did the following code changes
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
show_log(){
var lnk = "fetchlog.php";
$.ajax({url:lnk,success:function(result){
$("#log_div").html(result);
}});
}
window.setInterval(function(){
show_log();
}, 10000);
</script>
</head>
<body>
<div id="log_div"></div>
</body>
</html>
Whats wrong with my code as it doesn't fetch from fetchlog.php
fetchlog.php echo something like this
1. Acct_1 logged to the system.
2. Acct_3 logged in to the system.
3. Acct_2 logged in to the system.
4. Assign permissions on Acct_1.
5. Delete record on table building with id 80
jsFiddle
Yes you can use ajax for this and simply update a div in your html.
You need to have jquery linked in order to use the below code.
show_log(){
var lnk = "link to the viewlog.php file";
$.ajax({url:lnk,success:function(result){
$("#log_div").html(result);
}});
}
Run the show_log() function every x number of mins.
Have your viewlog.php show the last x number of records in the descending order of time.
You can update your sql to look like
$sql = "select log_description,log_time from log ORDER by log_time DESC LIMIT 5 ";
You can use the below inside your javascript to run the function every x number of seconds. In this every 10 seconds.
window.setInterval(function(){
show_log();
}, 10000);
the 10,000 is in miliseconds
----- Try the below
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
http = getHTTPObject();
function getHTTPObject(){
var xmlhttp;
if(!xmlhttp && typeof XMLHttpRequest != 'undefined'){
try {
xmlhttp = new XMLHttpRequest();
}catch(e){
xmlhttp = false;
}
}
return xmlhttp;
}
function show_log(){
var url = "viewlog.php";
http.open("GET", url, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function handleHttpResponse(){
if(http.readyState == 4){
document.getElementById('log_div').innerHTML = http.responseText;
}
}
setInterval ( "show_log()", 5000 );
</script>
</head>
<body>
<div id="log_div"></div>
</body>
</html>

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/

javascript timer not counting down when retrieving time from db

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.

Categories