Jump to content

How to show Jquery countdown timer within php foreach loop?


man5

Recommended Posts

I am retriving records from mysql database that has expiry time limit.  The time in the database is saved in "minutes".  So for one hour, it'll be "3600" minutes.   That's all fine.

 

Now what I am trying to do is create a countdown clock using Javascript/jquery and I have ran into a bit of a problem.

 

1. I am retriving multiple records from the database that all have a countdown timer.  Currently, it's only taking the time value of the first record and using that for all the records.  I would like to know how I can make it so that each record will have it's own countdown timer value?

 

2. Everytime I refresh a page, it will reset the timer.  How can I fix this?

 

Here's my code.

<?php 

foreach($rows as $row) {
  $get_expiry_time =  $row['expiry_time'];

  <div class="record">
   <div class="timer">
   </div>
  </div>
}

?>

<script>
		$(document).ready(function(){
			var countDownTime = <?php echo $get_expiry_time; ?>;
			function countDownTimer() {
				var hours = parseInt( countDownTime / 3600 ) % 24;
				var minutes = parseInt( countDownTime / 60 ) % 60;
				var seconds = countDownTime % 60;
				var result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds  < 10 ? "0" + seconds : seconds);
				$('.timer').html(result);
				if(countDownTime == 0 ){ countDownTime = 60*60*60; }
				countDownTime = countDownTime - 1;
				setTimeout(function(){ countDownTimer() }, 1000);
			}
			countDownTimer();
		});	
		</script>
Edited by man5
Link to comment
Share on other sites

Your loop doesn't get you anywhere, because you just keep overwriting the same variable. Also, never write PHP variables directly into JavaScript contexts. This can lead to anything from syntax errors to full-blown cross-site scripting vulnerabilities.

 

If you want the timer to keep running, you need to store the time when it was started. This can be done server-side or client-side, depending on your requirements. If the timer is important and must not be reset by the user, you need an additional timestamp column which you set as soon as you retrieve the record for the first time. If the timer is just-for-fun, you may use a cookie instead.

 

The table for the server-side solution would look something like this:

- record_id INT
- expiry_minutes INT UNSIGNED
- expiry_start DATETIME (initially NULL)
- ...

Before you retrieve the records, you first initialize the expiry starts which haven't been initialized yet. Then you can calculate the remaining time for each record:

db("update records set expiry_start = now() where record_owner = <current_user> and expiry_start is NULL")

records := db("select records where record_owner = <current_user>")
foreach record in records:
  remaining_time := record.expiry_start + record.expiry_minutes - now()
  ...

There are two ways for safely passing the timer values to JavaScript:

  • You first send all records as plain HTML. Then you make an Ajax request to retrieve the timer values and start the timers.
  • In your PHP code, you create a JSON object while you retrieve the rows and embed that object into a hidden HTML element. Then your JavaScript code can parse the data and create the timers.

Pick whatever you like best. The latter is a bit easier to implement, because you don't need any Ajax requests.

Link to comment
Share on other sites

clear explanation of picture from Jacques1. how it can done properly.

 

but for learning purpose you can try below..

 

<?php 


foreach($rows as $row) {
  $get_expiry_time =  $row['expiry_time'];
  <div class="record">
   <div class="timer">
   </div>
  </div>
?>


<script>
$(document).ready(function(){
var countDownTime = <?php echo $get_expiry_time; ?>;
function countDownTimer() {
var hours = parseInt( countDownTime / 3600 ) % 24;
var minutes = parseInt( countDownTime / 60 ) % 60;
var seconds = countDownTime % 60;
var result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds  < 10 ? "0" + seconds : seconds);
$('.timer').html(result);
if(countDownTime == 0 ){ countDownTime = 60*60*60; }
countDownTime = countDownTime - 1;
setTimeout(function(){ countDownTimer() }, 1000);
}
countDownTimer();
}); 
</script>
<?php
}
?>
Link to comment
Share on other sites

This is something that I done over a year and half ago for fun, there are few things that I would change though it gives a good example of using json:

 

The PHP file : 

sendCountDown.02.php

<?php
date_default_timezone_set('America/Detroit'); // Set the Default Time Zone:

session_start();

$future = (isset($_SESSION['future'])) ?  $_SESSION['future'] :  '2015-12-25 00:00:00';

$expired = new DateTime($future);
$now = new DateTime();

$e['countDown'] = $now->diff($expired, true);

print json_encode($e); // JSON

web.countdown.ajax.02.js

$(function () {
    /*  The Countdown 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.02.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 = '';

                if (hours < 10) {
                    hours = '0' + hours;
                }

                if (minutes < 10) {
                    minutes = '0' + minutes;
                }

                if (seconds < 10) {
                    seconds = '0' + seconds;
                }

                $msg = days + ' Days ' + hours + ' Hours ' +
                        minutes + ' Minutes ' + seconds + ' Seconds';

                /* Display Time in Message */
                $clock.text($msg);

            },
            error: function (response) {
                var r = jQuery.parseJSON(response.responseText);
                alert("Message: " + r.Message);
                alert("StackTrace: " + r.StackTrace);
                alert("ExceptionType: " + r.ExceptionType);
            }
        }); // End of ajax call:

    } // End of Function:	

}); // END OF DOC READY:

and the main file countDownClock.php

<?php
session_start();
date_default_timezone_set('America/Detroit'); // Set the Default Time Zone:

if (isset($_POST['action']) && $_POST['action'] == 'enter') {
	$futureDate = date('Y-m-d H:i:s',strtotime($_POST['futureDate']));
	$_SESSION['future'] = $futureDate;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>The Count Down Clock</title>
<link rel="stylesheet" href="css/style.css">
</head>

<body>

<?php echo (isset($futureDate)) ? '<h1 class="container headingDate">' . $futureDate . '</h1>' : '<h1 class="container headingDate">Christmas Day is 2015-12-25</h1>'; ?>
<form id="countDownForm" class="container rounded shadow" action="countDownClock.php" method="post">
  <input type="hidden" name="action" value="enter">
  <label for="countDownStyle" class="cmsLabel">Enter Future Date: </label>
  <input id="countDownStyle" name="futureDate" value="" type="datetime" placeholder="0000-00-00 00:00:00" required>
  <input type="submit" name="submit" value="Submit" class="submitBtn">
</form>

<div class="container clockBox rounded shadow">
  <p class="clock"></p>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="web.countdown.ajax.02.js"></script>
</body>
</html>

I think it shows how one can pull the time from php; which in my opinion that the PHP language has better date/time functions/methods that jQuery/JavaScript in the first place. That can be pulled from a database or what have you. 

Edited by Strider64
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.