dynamic js countdown help

hey all,

i need a bit of JavaScript help, what i need is a script to display Days:Hours:Minutes:seconds and automatically count down to 0 then display “Expired” the times that would be used are from my database in Unix time-stamp format here is what i have. This will be in a table built with a while loop displaying many results from a table so i want to stay away from page refresh scripts, and i have been unable to locate a starter script as i am not a js person at all.

[php]
$eventCreated = $row[‘ban_created’];
$created = new DateTime();
$created->setTimestamp($eventCreated);
$created_ex = $created->format(‘m/d/Y’);
$end = new DateTime();
$end->setTimestamp($eventCreated + $eventLength);
$now = new DateTime();
$timeUntilEnd = $now->diff($end);
$minutes = $row[‘ban_length’];
$d = floor ($minutes / 1440);
$h = floor (($minutes - $d * 1440) / 60);
$m = $minutes - ($d * 1440) - ($h * 60);

<?php if ($row['ban_length'] == 0){ echo "PermaBan"; }else{ //This is where i need the countdown echo $timeUntilEnd->h .":".$timeUntilEnd->i.":".$timeUntilEnd->s. " Left" ; } ?>[/php]

First, I think this might be what you are looking for and second I wrote this mostly in jQuery (I like working in jQuery better), meaning you will need the jQuery library.

I also used AJAX, JSON and PHP, for I like working with PHP date functions better than JavaScript.

Here’s the php file called: sendCountDown.php

[php]<?php
date_default_timezone_set(‘America/Detroit’); // Set the Default Time Zone:
// $expired would be from a Table in a database in reality:
$expired = new DateTime(‘2014-07-04 12:00:00’);
$now = new DateTime();

$e[‘countDown’] = $now->diff($expired, true);
print json_encode($e); // JSON[/php]

As you can tell it is really simple and now here’s the HTML file:

[code]

Expired Countdown .centerClock { /* Rest of Styling in jQuery */ margin: 0 auto; }
[/code]

Again very simple and lastly here’s the jQuery file:
[php]$(function() {
/* The Timer to call the Ajax Method */
var updateTime = setInterval(displayTime, 1000);

/* The Ajax Method of Getting Time */
function displayTime() {
	var $clock = $('.clock');
	
		$.ajax({ // Start of ajax:
			url: 'sendCountDown.php',   // Pulling time from the server:         
			dataType: "json", // Format type:
			success: function(info) { // Grab the data from php and then display it:
				
				// Variables * Self-Explanatory *
				var days       =  info.countDown.days, // Grab total days till expiration:
						hours      =  info.countDown.h, // Grab total hours till expiration:
				    minutes    =  info.countDown.i, // Grab total mins till expiration:
						seconds    =  info.countDown.s, // Grab total secs till expiration:
						$msg       =  'Days: ' + days + ' Hours: ' + hours + 				
						' Minutes: ' + minutes + ' Seconds ' + seconds;
						
						/* Display Time in Message */				 
						$clock.text($msg);										
						
					},
					error: function(request, status, error) {
						alert(status + ", " + error);
					}
		}); // End of ajax call:
} // End of Function:

/*  I Just wanted to see if I could stle it in jQuery */
/*                 START SECTION                      */

$('.clockBox').css({
	'box-sizing' : 'border-box',
	'display'    : 'block',
	width       : '100%',
	'max-width'  : '500px',
	height      : '100%',
	'max-height' : '50px',
	'text-align' : 'center',
	padding     : '0 20px',
	'background-color' : 'rgba(102, 0, 0, 0.8)'
	 //margin            : '0 auto'	// DELETE THIS IF TO CONTROL IT FROM CSS:
	});

$('.clock').css({
	'font-family' : 'Arial, Helvetica, sans-serif',
	'font-size'   : '1.2rem',
	'line-height' : '50px',
	color        : '#fff',
	'letter-spacing' : '0.0850em'	
});

$('.rounded').css({
	'-webkit-border-radius' : 15,
	'-mox-border-radius'    : 15,
	'-ms-border-radius'     : 15,
	'-o-border-radius'      : 15,
	'border-radius'         : 15
});

$('.shadow').css({
	'-webkit-box-shadow'    : '2px 2px 3px rgba(0, 0, 0, 0.8)',
	'-moz-box-shadow'       : '2px 2px 3px rgba(0, 0, 0, 0.8)',
	'box-shadow'            : '2px 2px 3px rgba(0, 0, 0, 0.8)'
});

/*                 END SECTION                        */
/*          DELETE BETWEEN START & END                */
/*        THEN STYLE IT IN CSS IF DESIRED             */	

}); // END OF DOC READY:[/php]

Like I said I don’t know if this is what you are looking for, but the date(s) are pretty straight forward and can be formatted anyway you like. Hope this helps. :wink:

P.S. Setting up the expiration portion should be relatively simple, a separate function to check to see if the Date has expired would probably do the trick.

hey sorry it took me so long getting back to you on this, i greatly appreciate the code however i am trying to use this all in one script (sorry i didn’t mention that before), i am confined to pages used on this and get a bonus on style and singularity, its for a school project and i really need the bonus.

any idea on how to do this in a single script

i have 2 mysql fields (created{timestamp}, length{minutes})

so i have
[php]$created = $row[created];
$length = $row[length];
$now = time();
$end = $created+$length;
$left = $now-$end;[/php]

the desired output is ?Day(s) ??H:??M:??S Left

of which is where my weakness is … i suck at php and time as well as i know very very little about javascript

on my page i have a table built ( i know i should use css but since this is a quick build and will be styled later i am just going to use a table)

Name Date Created Date End Time Left BOB 4/7/2014 4/10/2014 3 Days 23:15:05 TOM 4/4/2014 4/12/2014 8 Days 23:15:05 JIM 4/3/2014 4/17/2014 14 Days 23:15:05 Ken 4/1/2014 4/23/2014 22 Days 23:15:05

how can i do this in a single page?

sorry for double post but i updated my code to show the vars a bit better
This is working flawlessly but it has to be manually refreshed, i would like it to just countdown via JavaScript

[php]$now = date(“Y-m-d H:i:s”,time());
$datetime1 = new DateTime($now);
$ban_created = $row[‘ban_created’];
$ban_length = $row[‘ban_length’];
$created = date(“Y-m-d H:i:s”,$ban_created);
$created2 = date(“m/d/Y”,$ban_created);
$expire = date(“Y-m-d H:i:s”,$ban_created+($ban_length*60));
$datetime2 = new DateTime($expire);
$interval = $datetime1->diff($datetime2);
$timeleft = “”;
if($now >= $expire){
$timeleft = “Expired”;
}else{
$timeleft = $interval->format(’%Dd %H:%I:%S’);
}[/php]

Hmm, if you could pull the data from the MySQL database from the same file the HTML page would that be considered one page? Though I don’t know how one would go about doing. It’s to bad for using AJAX and JSON keeps you away from page reloading. :frowning:

Hold on I might this might help, this script (though not a countdown counter) might steer you in the right direction:

[php] var $theTimeText = $(’.phpTime’).text(),
$phpTime = $(’.phpTime’),
$argTime = $theTimeText.split(’:’), // Split the time into an array:
period = $argTime[3], // ( AM OR PM ):
seconds = $argTime[2], // Seconds Variable:
minutes = $argTime[1], // Minutes Variable:
hour = $argTime[0], // HOur Variable:
dHour = hour; // Display Variable:[/php]

[php] /* The Timer that does the calculations */
var updateTime = setInterval(displayTime, 1000);

		function displayTime() {
			
			function hourlyFCN() {  // Create a Function to save repetition:
				
				if (hour > 24) {
					hour = 1; // Reset to One O'Clock if past 12 Midnight:
				}									
				if (hour < 10) {
					dHour = '0' + hour; // Add a leading zero if hour is less than 10:
				} else if ( hour >= 10 && hour <= 12) {
					dHour = hour; // For some strange reason it doesn't work with out this:
				}	
				
				if (hour > 12) { // Convert 24-hour format to 12-hour format:
					dHour = (hour - 12);
					if ( dHour < 10 ) {
						dHour = '0' + dHour;
					}
				}
				
												
				/* Change the Period (AM/PM) */					
				if ( hour >= 1 || hour == 24) period = 'AM';
				if ( hour > 11 && hour != 24) period = 'PM';								
			}
			
			seconds++; // Increment Seconds:
			if ( seconds < 10 ) {
				seconds = '0' + seconds; // Put leading zero on seconds < 10:
			}
			
			if ( seconds == 60 ) {
				seconds = '00'; // Reset Seconds to ZERO & Display properly: 
				minutes++; // Increment Minutes:
				if ( minutes < 10 ) {
					minutes = '0' + minutes; // Put leading zero on minutes < 10:
				}
				
				if ( minutes == 60) {
					minutes = '00'; // Reset Minutes to ZERO & Display properly:
					hour++;	// Increment Hour:	
				}
														
			}
		  
 			hourlyFCN(); // Change Hour to proper time if condition(s) are met:
			
			var $clock = $('.clock'); // p tag:
			/* Put text in p tag to create the clock */
			$clock.text( dHour + ':' + minutes + ':' + seconds + ' ' + period );
		}[/php]

[code]

<?php echo date('H:i:s:A'); ?>

[/code]

This way you could pull the time in HTML with php and manipulate it with JavaScript (or JQuery) and it would be one file. :wink:

You could have it any format you like, see http://php.net/manual/en/function.date.php for details on formatting. Of course pulling in data from the database would be a little more php coding and pulling it the date from MySql is pretty easy:

[php]$query = ‘Select id, content, DATE_FORMAT(dateUpdated, “%M %e, %Y”) as dateUpdated FROM pages WHERE id=:id’;[/php]
Do a Google search on Date_FORMAT in MySQL should help find the proper format or just pull in the timestamp date raw (dateUpdated for example) for it should be in the 0000-00-00 00:00:00 format already. Though doing the time manipulation in JavaScript isn’t my forte, sorry I won’t be able to help you out there. PHP is sure much easier. Darn it. :frowning: Though someone who knows more on AJAX and JSON probably still do it this way…sigh…

Sponsor our Newsletter | Privacy Policy | Terms of Service