PHP multiple timer function instances - php

I'm making a site where users post text posts and each post has a countdown timer on, different for each one. I am having a problem where I am only able to have one timer running.
I have a function to get the time depending on the time in the database for the post and the current time. The php file loops through each post and calls the time function to get the time for each post. However it is only creating one timer.
code for the timer
function getTime($conn, $pid){
$countDownDate;
$sql = "SELECT * FROM userposts";
$result = mysqli_query($conn,$sql);
while ($row = $result->fetch_assoc()){
if ($row['pid'] == $pid){ // getting the row of the user
$countDownDate = $row['time'];
}
}
echo "<p style='color:black' id='demo'></p>
<script>
// Set the date we're counting down to
var countDownDate = new Date('".$countDownDate."');
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id='demo'
document.getElementById('demo').innerHTML = days + 'd ' + hours + 'h '
+ minutes + 'm ' + seconds + 's ';
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById('demo').style.color = 'red';
document.getElementById('demo').style.fontWeight = '900';
document.getElementById('demo').innerHTML = 'EXPIRED';
}
}, 1000);
</script></br>";
}
code to get time in each post
function getPosts(){
while ($row = $result->fetch_assoc()){
echo "<div class='post-box'><p>";
// displaying time
getTime($conn,$row['pid']);
echo "</p></div>";
}
}
it is only displaying the time for the first post in the loop

Try using
class="demo"
instead of
id="demo"
The id attribute specifies a unique id for an HTML element (the value
must be unique within the HTML document).
Check
How to use HTML id Attribute

I'd change the getTime function with this one because I think you are getting only one record from that table:
function getTime($conn, $pid){
$countDownDate;
$sql = "SELECT * FROM userposts WHERE pid = '" . $pid . "'";
$result = mysqli_query($conn, $sql);
$row = $result->fetch_assoc();
$countDownDate = $row['time'];
echo '<p style="color: black;" class="counter" data-countdowndate="' . $countDownDate . '"></p><br />';
}
Then, the Javascript code would be writen only once for all counters, here is a working example:
var counters = document.getElementsByClassName('counter');
var intervals = new Array();
for (var i = 0, lng = counters.length; i < lng; i++) {
(function(i) {
var x = i;
// Update the count down every 1 second
intervals[i] = setInterval(function() {
var counterElement = counters[x];
var counterDate = counterElement.dataset.countdowndate;
// Set the date we're counting down to
var countDownDate = new Date(counterDate);
// Get current date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id='demo'
counterElement.innerHTML = days + 'd ' + hours + 'h ' + minutes + 'm ' + seconds + 's';
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(intervals[x]);
counterElement.style.color = 'red';
counterElement.style.fontWeight = '900';
counterElement.innerHTML = 'EXPIRED';
}
}, 1000);
})(i);
}
<span style="color:black" class="counter" data-countdowndate="2018-12-06 01:08:28"></span><br />
<span style="color:black" class="counter" data-countdowndate="2018-12-12 11:07:29"></span><br />
<span style="color:black" class="counter" data-countdowndate="2018-12-13 12:06:30"></span><br />
<span style="color:black" class="counter" data-countdowndate="2018-12-14 13:05:31"></span><br />
<span style="color:black" class="counter" data-countdowndate="2018-12-15 14:04:32"></span><br />

Related

Whatsapp sharing button with a countdown variable

Beginner in web coding, I have issue to code a sharing button that lead to whatsapp and that share a countdown.
I achieve it with static string but I can't load a variable in it...
Does someone know where my issue is please ?
<script>
// Set the date we're counting down to
var countDownDate = new Date("Aug 20, 2022 12:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
var countdown_iam = days + "j " + hours + "h "
+ minutes + "m " + seconds + "s "
// Output the result in an element with id="countdown"
document.getElementById("countdown").innerHTML = countdown_iam;
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "SURPRISE!!!";
}
}, 1000);
function openWhatsApp() {
//var countdown_whatsapp = "test";
//alert(countdown_iam);
window.open('whatsapp://send?text=' + countdown_iam);
}
</script>
<h2> WhatsApp sharing Link </h2>
<!-- create an image icon to open the WhatsApp onclick -->
<img src="img/whatsapp.png" height="50" size="50" onclick="openWhatsApp()">
Thank's for your help
The countdown_iam variable is created within a function and only exists within that function. So when the other function (openWhatsApp) tries to use the variable, it can't find it and the error occurs.
You want to access the countdown string from two different functions, so one option would be to create a new function that makes the countdown string and returns it. You can then call that function from both places. I've done that here:
<script>
function getCountdown() {
var countdownDate = new Date("Aug 20, 2022 12:00:00").getTime();
var now = new Date().getTime();
var distance = (countdownDate - now) / 1000;
if (distance < 0) {
return 'SURPRISE!!!';
} else {
var days = Math.floor(distance / (60 * 60 * 24));
var hours = Math.floor((distance % (60 * 60 * 24)) / (60 * 60));
var minutes = Math.floor((distance % (60 * 60)) / 60);
var seconds = Math.floor(distance % 60);
return days + "j " + hours + "h " + minutes + "m " + seconds + "s ";
}
}
function openWhatsApp() {
alert('whatsapp://send?text=' + getCountdown());
}
setInterval(function() {
document.getElementById("countdown").innerHTML = getCountdown();
}, 1000);
</script>
<h2>WhatsApp Sharing Link</h2>
<p id="countdown"></p>
<p><img src="img/whatsapp.png" height="50" size="50" onclick="openWhatsApp()"></p>

Use jquery inside php foreach into html (Laravel)

The main issue is my first row at the table (column:waktu) has no jquery countdown time
Table Screenshot at the bottom
This is the codes i try to use with laravel php
<tbody>
#php $k=0; #endphp
#foreach($maininformation as $inf)
#php
$dateTime = strtotime($inf->kapan);
$dateNow = strtotime(date("Y-m-d H:i:s"));
$tesss = date("M j, Y H:i:s", strtotime($inf->kapan));
$tanggals = date("M j, H:i:s", strtotime($inf->kapan));
$diff = $dateTime - $dateNow;
if($diff < 0){
$show = "Expired";
}else{
$show = "";
}
if($show!="Expired"){ $k++;
#endphp
<script>
$("td").each(function(){
<?php echo "var theDate = '{$tesss}';"; ?>
var countDownDate = new Date(theDate).getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
<?php echo "var increments = '{$k}';"; ?>
var res = "demo"+increments;
document.getElementById(res).innerHTML = days + " Hari " + hours + " Jam "
+ minutes + " Menit " + seconds + " Detik";
}, 1000);
});
</script>
<tr>
<?php
$result = 'demo'.$k;
?>
<td id="tableson" style="text-align: center;">{{$k}}</td>
<td id="tableson" style="text-align: center;">{{$inf->title}}</td>
<td id="tableson" style="text-align: center;">{{$inf->information}}</td>
<td>{{$tanggals}}<p id={{$result}}></p></td>
</tr>
#php } #endphp
#endforeach
</tbody>
i have already solved the loop issue but i dont know why my first row doesnt show the times ive do for the codes.
NOTES: im new to codes and try to do some logic so i can solve my problem so pls be kind to me (i just copy paste the jquery codes i got from internet and try to edit some of them to work like i want to do).
ive thinking about maybe different name variable caused the logic error, but why just the first row has empty value? ive try to add many row and delete some row, its working fine and just the first row has empty value.
this is the table i got:

PHP Countdown from Day Hour Minute Second

Want to show a countdown of Days Left, Hour, Minute, Second.
The time data comes in this format:
startTime: "2017-02-17T13:51:13",
I found a example script found on stack:
<?php
$now = new DateTime();
$ends = new DateTime('May 31, 2017, 11:59 pm');
$left = $now->diff($ends);
?>
<dd>
<div class="timer_wrp">Remaining
<ul class="timer countdown">
<li><i><?php echo $left->format('%a'); ?></i>Day</li>
<li><i><?php echo $left->format('%h'); ?></i>Hour</li>
<li><i><?php echo $left->format('%i'); ?></i>Min</li>
<li><i><?php echo $left->format('%s'); ?></i>Sec</li>
</ul>
</div>
The Date format is different, is there a easy way to use how its currently setup or would I have to change that into the example format? And do you see anything that maybe missing from this example? Thanks
check this. If you don't set the time zone your calculation may be wrong. Because, by default it takes the server time zone. It might have other solution but in my case, I always use javascript.
<?php
date_default_timezone_set("Asia/Calcutta");
$now = new DateTime();
$ends = new DateTime('Oct 9, 2020, 4:40:00');
$left = $now->diff($ends);
?>
<div class="timer">
<p>Remaining </p>
<ul class="timer countdown">
<li><i><?php echo $left->format('%a'); ?></i>Day</li>
<li><i><?php echo $left->format('%h'); ?></i>Hour</li>
<li><i><?php echo $left->format('%i'); ?></i>Min</li>
<li><i><?php echo $left->format('%s'); ?></i>Sec</li>
</ul>
</div>
You may need this one also. This one is written in javascript. Copy both and see the difference.
<p id="demo"></p>
<!--javascript-->
<script>
// Set the date we're counting down to
var countDownDate = new Date("Oct 9, 2020 4:40:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>

timestamp countdown in javascript and php

I need some help to code a script that counts down the days, hours, minutes and seconds from a unix timestamp.
timestamp is created with php
<? php echo hours ();?>
And I want the script to count down in real time with JavaScript.
Example
2 days, 3:15:39
Hope someone can help me a little:)
First you have some PHP errors. It should be e.g.
<?php echo time(); ?>
I'm using a timestamp in JavaScript for the ease of showing an example.
http://jsfiddle.net/pimvdb/AvXd3/
// the difference timestamp
var timestamp = (Date.now() + 1000 * 60 * 60 * 24 * 3) - Date.now();
timestamp /= 1000; // from ms to seconds
function component(x, v) {
return Math.floor(x / v);
}
var $div = $('div');
setInterval(function() { // execute code each second
timestamp--; // decrement timestamp with one second each second
var days = component(timestamp, 24 * 60 * 60), // calculate days from timestamp
hours = component(timestamp, 60 * 60) % 24, // hours
minutes = component(timestamp, 60) % 60, // minutes
seconds = component(timestamp, 1) % 60; // seconds
$div.html(days + " days, " + hours + ":" + minutes + ":" + seconds); // display
}, 1000); // interval each second = 1000 ms

Countdown Timer

My project in php
I want to create a countdown timer for asking question in limited timeframe like LMS
here i have use the javascript countdown timer but when refresh the page javascript timer are reset.
You could store the start time in a php session. Then everytime you load a page you can continue the countdown timer with javascript, e.g.
<?php
//on every page
session_start();
//when you start
$_SESSION['start_time'] = time();
Then on every page:
<script type="text/javascript">
var startTime = <?php echo $_SESSION['start_time']; ?>;
//calculate remaining time
</script>
You will need to watch for when the timezones are different, or when the client's clock is wrong. Maybe instead you could calculate the remaining time in seconds and print that into javascript on each page, but then you could have innacuracy over high latency connections etc.
Try something like:
<?php
session_start();
//to reset the saved countdown
if (!empty($_REQUEST['resetCountdown']))
{
unset($_SESSION['startTime']);
}
if (empty($_SESSION['startTime']))
{
$_SESSION['startTime'] = time();
}
//In seconds
$startTime = time() - $_SESSION['startTime'];
?>
<script type="text/javascript">
var countdown = 60; //in seconds
var startTime = <?php echo $startTime; ?>;
startCountdown(startTime, countdown);
function startCountdown(startFrom, duration)
{
//countdown implementation
}
</script>
You could also store the timer in a session variable in PHP so that when the page is refreshed the time is still preserved.
try this
<script>
// Set the date we're counting down to
var countDownDate = new Date("Aug 1, 2017 12:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
and also put this under body tag.
<p id="demo"></p>

Categories