Html/Js live update page - php

I am programming the website for my church hockey league, and I am trying to make a page with live updates. I am currently trying a setInterval() to signal php to update the time.txt which the live page can draw the time from. So the update.html has the time on it, this page sends the time to a php doc with a get function which writes the time to time.txt, then live.html gets the time every 5 secs with a setInterval(). In that 5 secs live.html keeps its own time, but needs to check every 5 for pauses or time changes.
The problem is this: the server cant handle updating time.txt every 2.5 seconds so I need a simpler method that doesn't require me to update time.txt every 2.5, but live.html still can get the time, pauses, and time changes.
Any help please.
Here is update.html
$('#play').click(function(){
if(pause == true){
$('#play').attr('src',"mup/pause.jpg");
$.get("mup/postt.php", {text: "11"});
pause = false;
} else {
$('#play').attr('src',"mup/play.jpg");
$.get("mup/postt.php", {text: "09"});
pause = true;
}
});
function updatet(){
if(sec < 10){
if(min < 10){
var clientmsg = "0" + min + ":0" + sec;
} else {
var clientmsg = min + ":0" + sec;
}
} else {
if(min < 10){
var clientmsg = "0" + min + ":" + sec;
} else {
var clientmsg = min + ":" + sec;
}
}
$.get("mup/postt.php", {text: clientmsg});
}
setInterval (timer, 1000);
setInterval (updatet, 3000);
all the variables are defined at the beginning of the doc.
here is live.html
function timer() {
if(stop == true){
$("#time").html("<h5>Game Stopped</h5>");
} else {
sec = sec-1;
if(sec <= -1){
sec = 59;
min = min-1;
if(min <= -1){
sec=0;
min=0;
}
}
$("#time").html("\<h2\>"+min+":"+sec+"\</h2\>");
}
}
loadLog() {
$.ajax({
url: "mup/time.txt",
cache: false,
success: function(html){
var min = html.charAt(0).concat(html.charAt(1));
var sec = html.charAt(3).concat(html.charAt(4));
var time = min + ":" + sec;
if(time == timel){
stop = true;
} else {
stop = false;
}
timel = time;
},
});
}
setInterval (loadLog, 5000);
setInterval (timer, 1000);
and at the beginning of the doc all variable were defined with timel and time being different. Post.php just puts the sent stuff onto the doc, so time.txt would look like "06:08" or whatever.aa

Related

JavaScript countdown from php timestamp difference

I'd like to countdown time which is difference between two time from php, the result is timestamp.
{var $time = new \DateTime()}
<div class="date" data-date="{= ($time2->getTimestamp() - $time->getTimestamp())*1000}">
In data-date I have difference of time [timestamp]. Now I want to countdown this time. I get this information from HTML to JS.
$(function() {
$(".date").each(function(){
time = $(this).data('date');
$.countdown($(this).children(".countdown"), time);
});
});
There is taken code which doesn't work properly.
jQuery.countdown = function(selector, datevalue) {
var amount = datevalue;
// catch past dates
if(amount < 0){
$(selector).html("Done");
}
// date is in the future, calculate the diff
else{
days=0;hours=0;mins=0;secs=0;out="";
amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs
days=Math.floor(amount/86400);//days
amount=amount%86400;
hours=Math.floor(amount/3600);//hours
amount=amount%3600;
mins=Math.floor(amount/60);//minutes
amount=amount%60;
secs=Math.floor(amount);//seconds
//if(days != 0){out += days +" day"+((days!=1)?"s":"")+", ";}
//if(days == 0) {
if(days != 0 || hours != 0){out += ((hours<10)?"0":"") + hours +":";}
if(days != 0 || hours != 0 || mins != 0){out += ((mins<10)?"0":"") + mins +":";}
out += ((secs<10)?"0":"") + secs;
$(selector).html(out);
//}
// run it all again
setTimeout(function() {
$.countdown(selector, datevalue);
}, 1000);
}
};
The time from JS is on the right place but it doesn't countdown.
The answer is very simple: you do not decrease datevalue variable. So its the same for all iterations
Look at the example below it works fine
jQuery.countdown = function(selector, datevalue) {
var amount = datevalue;
// catch past dates
if(amount < 0){
$(selector).html("Done");
}
// date is in the future, calculate the diff
else{
datevalue--;
$(selector).html(datevalue);
setTimeout(function() {
$.countdown(selector, datevalue);
}, 1000);
}
};
$.countdown('.date', 10);​​​

Countdown timer built on PHP and jQuery?

After spending the last 45 minutes looking around for a solution, I can't seem to find an easy solution to creating a countdown timer using PHP and jQuery. Most already built scripts I've found are based purely on jQuery which require a ton of code, and more parameters then they should, plus, adaptability is pretty hard.
Here's my situation;
PHP:
$countdown = date("h:i:s"); // This isn't my actual $countdown variable, just a placeholder
jQuery:
$(document).ready(function name() {
$("#this").load( function() {
setTimeout("name()", 1000)
}
}
});
HTML:
<div id="this"><?php echo($countdown); ?></div>
My idea is that, every second, #this is reloaded, giving a new value to it's contents, and as $countdown isn't a static variable, a new value will be loaded each time. This removes the need to deal with sessions (as a basic javascript countdown timer would reset on pageload, etc).
I would've though this would have worked, until I realized that the event binder .load() doesn't reload #this (I know silly me), so I guess what I'm wondering is - is there an event binder I can use to make this work or is there a way to get the functionality I'm looking for, without using a jQuery plugin (which doesn't match exactly what I want anyway)?
You should use Keith Wood's countdown timer: http://keith-wood.name/countdown.html
It is extremely easy to use.
All you have to do is
$('#timer').countdown({
until: '<?php echo date("h:i:s"); ?>' // change this, obviously
});
Here's the fiddle: http://jsfiddle.net/tqyj4/289/
OK, I know that an id is not a variable, but don't use this as an ID. It is makes people cringe.
To the rest, don't reload the value, set a value in JS in PHP and then count down.
// place this in the <head> above the code below
echo "var t = " . time() . ";";
echo "var ft = " . /* your final time here */ . ";";
Then:
// this is a helper function.
function lpad( input, len, padstr )
{
if( !padstr ) padstr = " "; // this is the normal default for pad.
var ret = String( input );
var dlen = ret.length - len;
if( dlen > 0 ) return ret;
for( var i = 0; i < dlen; i++ ) ret = padstr + ret;
return ret;
}
$(document).ready(function name() {
$("#timer").load( function() { // I changed the id
$timer = $("timer"); // might as well cache it.
// interval, not timeout. interval repeats
var intval = setInterval(function(){
t += 500; // decrease the difference in time
if( t >= ft )
{
t = ft; // prevent negative time.
clearInterval( intval ) // cleanup when done.
}
var dt = new Date(ft - t);
$timer.innerHTML = dt.getHours() + ":" +
// pad to make sure it is always 2 digits
lpad( dt.getMinutes(), 2, '0' ) + ":" +
lpad( dt.getSeconds(), 2, '0' );
}, 500) // increments of .5 seconds are more accurate
}
}
});
Once php has loaded a particular amount of time for the user, can you explain why this wouldn't be sufficient for your needs:
$(function(){
$timerdiv = $("#this");
timer();
});
function timer()
{
$timerdiv.html((int)$timerdiv.html() - 1);
setTimeout(timer, 1000);
}
You are very close in your original code. Here's a modification to your code below that works as described, or at least so I think - I know it works, but am not sure if it meets your requirements, they were a little unclear. Obviously if you reload the page, you would have to rely on the PHP output to be different in order for the counter to not reset. Just to note though, I'm not entirely sure why you would use the .load function - that function is really just a wrapper for an AJAX call to grab the contents of another page and insert it into the selected div. I believe what you're looking for is the .html() function to change the contents of the selected div using the content available in the DOM vs. making an AJAX request.
var timer;
$(document).ready(
name();
);
function name() {
//clear the timer
clearTimeout(timer);
//reset the timer
timer = setTimeout("name()", 1000);
//grab the current time value in the div
var time = $("#this").html();
//split times
var time_splits = time.split(":");
//add up total seconds
var total_time = (parseInt(time_splits[0])*60*60) + (parseInt(time_splits[1])*60) + parseInt(time_splits[2]);
//subtract 1 second from time
total_time -= 1;
//turn total time back in hours, minutes, and seconds
var hours = parseInt(total_time / 3600);
total_time %= 3600;
var minutes = parseInt(total_time / 60);
var seconds = total_time % 60;
//set new time variable
var new_time = (hours < 10 ? "0" : "") + hours + (minutes < 10 ? ":0" : ":" ) + minutes + (seconds < 10 ? ":0" : ":" ) + seconds;
//set html to new time
$("#this").html(new_time);
}
$dateFormat = “d F Y — g:i a”;
$targetDate = $futureDate;//Change the 25 to however many minutes you want to countdown change date in strtotime
$actualDate = $date1;
$secondsDiff = $targetDate – $actualDate;
$remainingDay = floor($secondsDiff/60/60/24);
$remainingHour = floor(($secondsDiff-($remainingDay*60*60*24))/60/60);
$remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))/60);
$remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))-($remainingMinutes*60));
$actualDateDisplay = date($dateFormat,$actualDate);
$targetDateDisplay = date($dateFormat,$targetDate);
<script type=”text/javascript”>
var days = <?php echo $remainingDay; ?>
var hours = <?php echo $remainingHour; ?>
var minutes = <?php echo $remainingMinutes; ?>
var seconds = <?php echo $remainingSeconds; ?>
function setCountDown(statusfun)
{//alert(seconds);
var SD;
if(days >= 0 && minutes >= 0){
var dataReturn = jQuery.ajax({
type: “GET”,
url: “<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB).’index.php/countdowncont/’; ?>”,
async: true,
success: function(data){
var data = data.split(“/”);
day = data[0];
hours = data[1];
minutes = data[2];
seconds = data[3];
}
});
seconds–;
if (seconds < 0){
minutes–;
seconds = 59
}
if (minutes < 0){
hours–;
minutes = 59
}
if (hours < 0){
days–;
hours = 23
}
document.getElementById(“remain”).style.display = “block”;
document.getElementById(“remain”).innerHTML = ” Your Product Reverse For “+minutes+” minutes, “+seconds+” seconds”;
SD=window.setTimeout( “setCountDown()”, 1000 );
}else{
document.getElementById(“remain”).innerHTML = “”;
seconds = “00″; window.clearTimeout(SD);
jQuery.ajax({
type: “GET”,
url: “<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB).’index.php/countdown/’; ?>”,
async: false,
success: function(html){
}
});
document.getElementById(“remain”).innerHTML = “”;
window.location = document.URL; // Add your redirect url
}
}
</script>
<?php
if($date1 < $futureDate && ($qtyCart > 0)){ ?>
<script type=”text/javascript”>
setCountDown();
</script>
<?php }else{ ?>
<style>
#remain{display:none;}
</style>
<?php }}?>
<div id=”remain”></div>
For more information visit urfusion
#epascarello answer for your question in you need to pass the loop value in selector with id for example
$("#timer<? php echo $loopval; ?>")
and also call the it in the
<div id="timer<?php echo $loopval; ?>">
</div>

PHP JavaScript Countdown Timer

I need to make a countdown timer that displays a specific number of minutes and seconds counting down - not a countdown to a certain date.
And depending on a variable, change these numbers.
So for $video == 1, I need to display on the page: 8 minutes & 54 seconds (counting down)
And for $video == 2, I need to display on the page: 5 minutes & 01 seconds (counting down)
I also need the countdown display to disappear after the time has elapsed, but maybe I should put that into a different question.
The problem I'm having is the all the countdown scripts I can find deal with counting down to a specific date.
Everything you need, just enter the total time in seconds in the <span> tags. 30 and 120 here for demo. Should work if you copy and paste directly into a webpage. Add and edit code as needed.
<span id="countdown-1">30 seconds</span>
<span id="countdown-2">120 seconds</span>
<script type="text/javascript">
// Initialize clock countdowns by using the total seconds in the elements tag
secs = parseInt(document.getElementById('countdown-1').innerHTML,10);
setTimeout("countdown('countdown-1',"+secs+")", 1000);
secs = parseInt(document.getElementById('countdown-2').innerHTML,10);
setTimeout("countdown('countdown-2',"+secs+")", 1000);
/**
* Countdown function
* Clock count downs to 0:00 then hides the element holding the clock
* #param id Element ID of clock placeholder
* #param timer Total seconds to display clock
*/
function countdown(id, timer){
timer--;
minRemain = Math.floor(timer / 60);
secsRemain = new String(timer - (minRemain * 60));
// Pad the string with leading 0 if less than 2 chars long
if (secsRemain.length < 2) {
secsRemain = '0' + secsRemain;
}
// String format the remaining time
clock = minRemain + ":" + secsRemain;
document.getElementById(id).innerHTML = clock;
if ( timer > 0 ) {
// Time still remains, call this function again in 1 sec
setTimeout("countdown('" + id + "'," + timer + ")", 1000);
} else {
// Time is out! Hide the countdown
document.getElementById(id).style.display = 'none';
}
}
</script>
Try:
var x, secs = 600; //declared globally
x = setInterval(myFunc, 1000);
function myFunc()
{
document.getElementById('timer').innerHTML = secs; //assuming there is a label with id 'timer'
secs --;
if(secs == 0)
{
document.getElementById('timer').style.hidden = true;
clearInterval(x);
}
}
There is a countdown script located at http://javascript.internet.com/time-date/countdown-timer.html that doesn't countdown to a date but rather a specified amount of minutes.
The code may be customized as follows to get the desired effect
<?php
if ($video===1){
$time="8:54";
}
if ($video===2){
$time="5:01";
}
?>
<script type="text/javascript" src="countDown.js"></script>
<form name="cd">
<input id="txt" readonly="true" type="text" value="<?php echo $time; ?>" border="0" name="disp">
</form>
Make sure that the contents of countDown.js looks like this:
/* This script and many more are available free online at
The JavaScript Source :: http://javascript.internet.com
Created by: Neill Broderick :: http://www.bespoke-software-solutions.co.uk/downloads/downjs.php */
var mins
var secs;
function cd() {
mins = 1 * m("10"); // change minutes here
secs = 0 + s(":01"); // change seconds here (always add an additional second to your total)
redo();
}
function m(obj) {
for(var i = 0; i < obj.length; i++) {
if(obj.substring(i, i + 1) == ":")
break;
}
return(obj.substring(0, i));
}
function s(obj) {
for(var i = 0; i < obj.length; i++) {
if(obj.substring(i, i + 1) == ":")
break;
}
return(obj.substring(i + 1, obj.length));
}
function dis(mins,secs) {
var disp;
if(mins <= 9) {
disp = " 0";
} else {
disp = " ";
}
disp += mins + ":";
if(secs <= 9) {
disp += "0" + secs;
} else {
disp += secs;
}
return(disp);
}
function redo() {
secs--;
if(secs == -1) {
secs = 59;
mins--;
}
document.cd.disp.value = dis(mins,secs); // setup additional displays here.
if((mins == 0) && (secs == 0)) {
window.alert("Time is up. Press OK to continue."); // change timeout message as required
// window.location = "yourpage.htm" // redirects to specified page once timer ends and ok button is pressed
} else {
cd = setTimeout("redo()",1000);
}
}
function init() {
cd();
}
window.onload = init;
<?php
$countDownTime = 0;
if ($video == 1) $countDownTime = (8*60 + 54);
else if ($video == 2) $countDownTime = (5*60 + 1);
echo '<script>var countdownTime="' . $countDownTime . '";</script>"';
?>
<script>
<!-- as per the hyper linked reference below -->
$(selector).countdown({until: countdownTime});
</script>
Using the following library, you can implement a JQuery timer using the var countdownTime you specify above...
http://keith-wood.name/countdown.html <-- tutorial on the first page!
Edit Replaced $someTimeInSeconds with $countDownTime
Ok, I'm looking at doing something similar. Currently I have a simple countdown timer that is based off of current time that counts down every 30min. The problem is that I have to use a meta refresh to update it. I'm wondering if a combination of javascript and PHP might be a simpler solution to this answer. Use javascript to call the php code and automatically update it? Maybe set a variable for the time in the php script to be called with javascript? Well, here's the code I have that might help. I'm still learning.
$minutes_left = ($minutes)?((30 - $minutes)-(($seconds)?1:0)):0;
$minutes_left = str_pad ($minutes_left , 2, '0', STR_PAD_LEFT);
$seconds_left = ($seconds)?(60 - $seconds):0;
$seconds_left = str_pad ($seconds_left , 2, '0', STR_PAD_LEFT);
echo '<center><h1 style="font-color:white;">Next station break in: '.$minutes_left.'m '.$seconds_left.'s</h2></center>';
?>
I just have to figure out how to get it to reset itself at the end of every 30min and to update without meta refresh.

2 javascript functions clashing?

I am trying to implement a Javascript/PHP/AJAX clock into my website so that I can have a simple clock which can operate in different timezones (tutorial is here http://networking.mydesigntool.com/viewtopic.php?tid=373&id=31)
This itself works fine, but I already have a javascript stopwatch running on the page, and the 2 seem to clash and the clock won't display while the stopwatch is working.
This is the script for the clock:
<script type="text/javascript">
function loadTime ()
{
http_request = false;
if(window.XMLHttpRequest)
{
// Mozilla, Safari,...
http_request = new XMLHttpRequest();
if(http_request.overrideMimeType)
{
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
}
else if(window.ActiveXObject)
{ // IE
try
{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
}
}
}
var parameters = "time=";
http_request.onreadystatechange = alertContents;
http_request.open('POST', 'time.php', true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function alertContents()
{
if (http_request.readyState == 4)
{
if (http_request.status == 200)
{
result = http_request.responseText;
document.getElementById('clock').innerHTML = result;
}
}
}
</script>
<body onload="setInterval('loadTime()', 200);">
and this is the code for the stopwatch:
<script 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>
Could someone help me get them to work side-by-side please?
Thanks for any help
For one, your’re declaring an onload event handler in your HTML:
<body onload="setInterval('loadTime()', 200);">
which is consequently overwritten in script:
window.onload = function()
{
stopwatch('Start');
}
This means the original onload call is never executed.
You should try using addEventListener so you can add multiple event handlers to the same event.
A couple more points:
Don’t pass a string to setInterval and setTimeout, just pass the function itself. More efficient and less error-prone: setInterval(loadTime, 200);
Instead of writing all that JS code to work with different browsers, use jQuery, mootools, or one of the gazillion other frameworks. They make it a lot easier to get it right on all browsers.
Try this:
See the subtle '+=' instead of '=' !
window.onload += function()
{
stopwatch('Start');
}

java script timer problem

i have the following code in timer.php . If i run the file timer.php i get proper output as follows
time left : 02 min 30 sec
and this keeps on decreasing.
But if include the file timper.php in other files using <? require 'timer.php' ?> only time left : is shown and actual timer countdown is not shown (in Fire fox). But if i run same thing in ie it is shown correclty.
what is the problem? My timer.php has the flowing code.
<script >
var sec = 00; // set the seconds
var min = 02 // set the minutes
function countDown() {
sec--;
if (sec == -01) {
sec = 59;
min = min - 1;
} else {
min = min;
}
if (sec<=9) { sec = "0" + sec; }
time = (min<=9 ? "0" + min : min) + " min and " + sec + " sec ";
if (document.getElementById) { theTime.innerHTML = time; }
SD=window.setTimeout("countDown();", 1000);
if (min == '00' && sec == '00') { sec = "00"; window.clearTimeout(SD); }
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
countDown();
});
</script>
time left :
<span id="theTime" ></span>
Can anyone giv me a code for javascript countdown timer (in minutes) that i can copy pase in my project?
Just in case that it's not a typo or "abbreviation": You have to put quotes around the file name.
<?php require 'timer.php' ?>
Otherwise php will look for the constants timer and php and when it doesn't find them it will interpret them as two separate strings and concatenate them because the dot is interpreted as an operator, resulting in two warnings (about the missing constants) and require 'timerphp' (without the dot between timer and php)
If this code JS works for you, you have a problem with window.onload.
<script >
var countDown = function(idEl) {
this.sec = 00; // set the seconds
this.min = 02; // set the minutes
this.el = idEl; // set the minutes
this.SD = null;
this.timer = function(pthis) {
pthis.sec--;
if (pthis.sec == -01) {
pthis.sec = 59;
pthis.min = pthis.min - 1;
} else {
pthis.min = pthis.min; //??
}
if (pthis.sec<=9) { pthis.sec = "0" + pthis.sec; }
var time = (pthis.min<=9 ? "0" + pthis.min : pthis.min) + " min and " + pthis.sec + " sec ";
if (document.getElementById) { document.getElementById(pthis.el).innerHTML = time; }
pthis.SD=window.setTimeout(function(){pthis.timer.apply(pthis, [pthis])}, 1000);
if (pthis.min == '00' && pthis.sec == '00') { pthis.sec = "00"; window.clearTimeout(pthis.SD); }
};
this.timer(this);
}
</script>
time left : <span id="theTime" ></span>
<script>countDown("theTime")</script>
Here's my version of a JS countdown timer (FYI, I tested your version in Firefox and it worked fine for me).
<html>
<head>
<title>Timer</title>
<script type="text/javascript">
var Timer = {
// Main method for counting down
countDown: function (displayID, min, sec, callback) {
// Update timer display
document.getElementById(displayID).innerHTML = (min < 10 ? "0" : "") + min + ":" + (sec < 10 ? "0" : "") + sec;
// If there is time left on the timer, continue counting down
if (sec > 0 || min > 0) {
setTimeout(function () { Timer._countDownCallback(displayID, min, sec, callback); }, 1000);
}
// When time has run out invoke option callback function
else if (typeof callback == "function") {
callback();
}
},
// Internal method for processing remaining time
_countDownCallback: function (displayID, min, sec, callback) {
// Update time left for the timer
sec = (sec > 0 ? sec - 1 : 59);
if (sec == 59) min = (min > 0 ? min - 1 : 59);
// Call main method to update display, etc.
Timer.countDown(displayID, min, sec, callback);
}
};
// Start the timer when the page loads
window.onload = function () {
Timer.countDown("timerDisplay", 2, 30, function () { alert("The time has come!"); });
}
</script>
</head>
<body>
<div>Time left: <span id="timerDisplay"></span></div>
</body>
</html>
You can use this JavaScript Timer class.
Most likely the javascript in timer.php is not running properly because including the file in the other file cause the HTML to break due to some HTML tag mismatch. Or possibly there is another error in the external HTML page that breaks javascript for that. Without any more details its hard to tell as the Javascript code you shown - though I don't really like it and it has many problems - should work as you intended.

Categories