Use jquery inside php foreach into html (Laravel) - php

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:

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>

PHP multiple timer function instances

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 />

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>

How to make a countdown using PHP

Im creating a website for my brothers wedding. And so far all is going well. However, he wants a countdown to the wedding on the homepage;
Time left until the wedding: X months, X days, X hours.
I would preferebly like to do this using php, but would be open to other suggestions.
if you can help me with ideas for the coding, or just point me to relevant material, that would be useful.
The wedding is on Saturday 30th July.
If your need your counter to be displayed only on page refresh and be static once the page is loaded, then PHP will be fine.
If you need the countdown to get refreshed when the page is displayed, you'll need to use JavaScript.
Personally I would go for something already implemented, like that small script.
Following is the code snippet I have copied from the W3Schools website, while added my PHP code to get the "countdown to" timestamp and the "now" timestamp.
You will see I have commented out the original JavaScript code and replaced it with PHP code in two places, so it's clear to tell what's the difference between two options.
Basically when you think the "server time" is more reliable in your case, you can adopt the PHP approach.
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
</style>
</head>
<body>
<p id="demo"></p>
<script>
// Set the date we're counting down to
// 1. JavaScript
// var countDownDate = new Date("Sep 5, 2018 15:37:25").getTime();
// 2. PHP
var countDownDate = <?php echo strtotime('Sep 5, 2018 15:37:25') ?> * 1000;
var now = <?php echo time() ?> * 1000;
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
// 1. JavaScript
// var now = new Date().getTime();
// 2. PHP
now = now + 1000;
// 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>
</body>
</html>
For Static Countdown :
<?php
//A: RECORDS TODAY'S Date And Time
$today = time();
//B: RECORDS Date And Time OF YOUR EVENT
$event = mktime(0,0,0,12,25,2006);
//C: COMPUTES THE DAYS UNTIL THE EVENT.
$countdown = round(($event - $today)/86400);
//D: DISPLAYS COUNTDOWN UNTIL EVENT
echo "$countdown days until Christmas";
?>
$wedding = strtotime("2011-07-01 12:00:00+0400"); // or whenever the wedding is
$secondsLeft = $wedding - time();
$days = floor($secondsLeft / 60*60*24);
$hours = floor(($secondsLeft - $days*60*60*24) / 60*60);
echo "$days days and $hours hours left";
Code top by user Neil E. Pearson didnĀ“t work, he forgot to write there the brackets (), working solution is:
$wedding = strtotime("2011-07-01 12:00:00+0400"); // or whenever the wedding is
$secondsLeft = $wedding - time();
$days = floor($secondsLeft / (60*60*24)); // here the brackets
$hours = floor(($secondsLeft - ($days*60*60*24)) / (60*60)); // and here too
echo "$days days and $hours hours left";
$Target_Date = 1699458858; //expire data
$Time_Left = $Target_Date - time();
$days = floor($Time_Left / (60*60*24));//day
$Time_Left %= (60 * 60 * 24);
$hours = floor($Time_Left / (60 * 60));//hour
$Time_Left %= (60 * 60);
$min = floor($Time_Left / 60);//min
$Time_Left %= 60;
$sec = $Time_Left;//sec
echo "$days days and $hours hours and $min min and $sec sec left";
I would not use php (serverside) for this. Because you need to refresh your page every time to see the counting. Preferably use javascript (clientside) for this, more specific jquery (javascript framework). And look for a jquery plugin such as: http://keith-wood.name/countdown.html
If you want something realtime, you'll need to use client-side scripting, namely JavaScript.
You can do it in PHP, but it won't "animate":
$wedding = strtotime("2011-07-01 12:00:00+0400"); // or whenever the wedding is
$secondsLeft = $wedding - time();
$days = floor($secondsLeft / 60*60*24);
$hours = floor(($secondsLeft - $days*60*60*24) / 60*60);
echo "$days days and $hours hours left";
You could put some more math in for months, but it gets fuzzier because a month isn't a fixed amount of time.
The other way would be to use the date() function to pick out the individual elements (hour, minute, second, day, month etc) and use rollover math, but it's a lot of bother for a 'nice effect'.
Let me know if you want a JavaScript example. Don't bother with jQuery - it's a canon for killing a mosquito :)
try this
<?php
$target = mktime(0, 0, 0, 9, 25, 2011) ;//set marriage date
$today = time () ;
$difference =($target-$today) ;
$month =date('m',$difference) ;
$days =date('d',$difference) ;
$hours =date('h',$difference) ;
print $month." month".$days." days".$hours."hours left";
?>
Try this
$wedding = strtotime("2014-02-20 12:00:00"); // or whenever the wedding is
$current=strtotime('now');
$diffference =$wedding-$current;
$days=floor($diffference / (60*60*24));
echo "$days days left";
Try this static countdown.
<?php
//Current Date And Time
$todaytime = time();
//Set Date And Time OF The Event
$eventdate = mktime(0,0,0,0,28,2021);
//Calculate Days Until The Event
$countdown = round(($eventdate - $todaytime)/86400);
//Display Countdown
echo "$countdown days until the event";
?>

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