Why Will Jquery Countdown Timer Not Accept PHP Date? - javascript

I am using the Jquery "Final Countdown" Timer (found here: http://hilios.github.io/jQuery.countdown/) but I am modifying it to countdown from a date which is specified from a php var, like so:
PHP:
$gametimestamp = date("Y/m/d H:i:s", strtotime($gametimestamp));
Javascript:
var plustime = new Date(<?php echo $gametimestamp; ?>);
plustime.setSeconds(plustime.getSeconds() + 30);
$("#timerinsert")
.countdown(plustime, function(event) {
$(this).text(
event.strftime('%M:%S')
);
});
If
var plustime = new Date(<?php echo $gametimestamp; ?>);
Outputs like:
var plustime = new Date(2017/03/04 20:19:10);
Then why is the countdown timer not displaying? It DOES work if I just use
date();

You have to add quotes when echoing strings to javascript
var plustime = new Date("<?php echo $gametimestamp; ?>");
And note that new Date accepts a certain format, preferably you'd echo seconds from epoch instead, and add three zeros
$gametimestamp = strtotime($gametimestamp); // Unix timestamp in seconds
and then
var plustime = new Date(<?php echo $gametimestamp; ?> * 1000); // in milliseconds

Related

Jquery : Pass date from php format to a JS variable

i am receving start and end dates from a proc in following format
Array
(
[0] => Array
(
[min_created_date] => 2020-10-28 00:00:00.000
[max_created_date] => 2020-11-11 00:00:00.000
)
)
i have stored the values in below variables with the following outputs resepectively :
$start_range =$slider_range[0]['min_created_date'];
$start_range=substr($start_range, 0, strrpos($start_range, ' '));
$end_range= $slider_range[0]['max_created_date'];
$end_range=substr($end_range, 0, strrpos($end_range, ' '));
2020-10-28
2020-11-11
now i need to pass these dates to a jQuery function , i want to store this date to js variable since few js opetaions have to be performed to these dates further , Below is how i am trying to pass the dates
$(function() {
var startrange = <?php echo $start_range;?>;
var endrange = <?php echo $end_range;?>;
console.log(startrange+'startrange');
console.log(endrange+'endrange');
});
I get following in console :
1982startrange
1998endrange
please guide me how can i pass the dates to JS variables instead of <?php echo $date ?>
You have no other way to publish PHP variables in JavaScript without echo.
A cleaner way to do it to assign PHP variables to JavaScript vars inside a <script> tag so that PHP echo are not everywhere in your JS code.
<script type="text/javascript">
var startrange = '<?php echo $start_range; ?>';
var endrange = '<?php echo $end_range; ?>';
</script>
you have a lot of options, but i love unixtimestamp formats more ^^
PHP
$minCreatedDate = time();
$maxCreatedDate = strtotime('2020-11-11 00:00:00.000');
JS echoed in PHP file
var startrange = new Date(<?= $minCreatedDate ?> * 1000);
Date instance contains a lot of funcs. like "getDay", ...

Refresh content/page on the hour every hour

I have a code that is meant to refresh the page on the hour, every hour but it doesn't seem to execute...
This is the code:
<?php
date_default_timezone_set('Australia/Sydney');
$date = date("i:s");
list($cur_min, $cur_sec) = explode(':', $date);
$mins_left = ($cur_min == 59) ? 0 : 60 - $cur_min;
$secs_left = 60 - $cur_sec;
$time=($mins_left*60+$secs_left)*1000;
?>
<script type="text/javascript">
setInterval("refresh()",<?php echo $time; ?>);
function refresh(){
window.location = location.href;
}
</script>
I need it to run off the server clock too and not from when the user lands on the page.
Idealy, would be awesome if it could just refresh the content of every div labeled with the class named "locality"...
I would use DateTime in PHP and for easy convertion use timestamps.
$date = new \DateTime(strtotime(time()), new \DateTimeZone("Australia/Sydney")));
$date->add(new \DateInterval('PT1H'));
$time = $date->format('U') % 3600;
And for JS:
var time = (Math.round((new Date()).getTime() / 1000) % 3600);
if(time > <?= $time ?>){
var rtime = time - <?= $time ?>;
} else {
var rtime = <?= $time ?> - time;
}
setInterval(function(){
window.location.reload(1);
},rtime * 1000);
But im not sure why:
<meta http-equiv="refresh" content="3600">
Will not suffice as it will just refresh an hour later (and so on) of when the user enters the page, doesn't really matter what timezone.
Try this code for the JavaScript part:
function refresh(){
window.location.reload();
}
setTimeout(refresh, <?php echo $time; ?>);
I'm not sure if it will solve your problem, but I tried a few changes:
window.location.reload() is more explicit than window.location = location.href (which, by the way, could be simplified to window.location = window.location)
setTimeout instead of setInterval because if the refreshing fails again for some reason, you don't want to try refreshing again in
put the setTimeout call after the definition of the function to be sure that there isn't a problem with the function not being defined yet
Try it. If that code still doesn't work for you, try looking at your generated HTML and seeing what value for $time was printed. Also check the browser console for any errors.
By the way, the code would be clearer if you renamed the variable $time to $ms_until_start_of_hour.

how to convert strtotime in php to new Date in js

For a realtime countdown i use some php variables and echo them in the js like below:
$expire_year = '2016'; // year
$expire_month = '8'; // month ( 8 = August)
$expire_day = '14'; // day (14th)
$expire_hour = '2'; // hour ( 1-24)
$expire_minutes = '12'; // minutes
i use them in the js like blow:
timestamp = new Date(<?php echo $expire_year; ?>, <?php echo $expire_month - 1; ?>, <?php echo $expire_day; ?>, <?php echo $expire_hour; ?>, <?php echo $expire_minutes; ?>),
This works fine!
I use php strtotime to check if the date really has expired:
$quickpollexpiredate = strtotime("August 14, 2016 2:12"); // set an expiration date
So for the countdown timer in js and for the check in php, i have to use 2 different date "structures".
Is it possible to make a check in php so that i have to use only the 5 variables ($expire_year, $expire_month...) with strtotime() or another function?
So actually what i want to achieve is something like this (ofcourse this is wrong, but i hope you understand what i am trying to achieve)
$quickpollexpiredate = strtotime($expire_year, $expire_month, $expire_day, $expire_hour, $expire_minutes); // set an expiration date
If you have a timestamp in php, you can easily use it to set a Date object in javascript. You just need to consider that a timestamp in javascript is in milliseconds and not seconds like in php:
jsTimestamp = new Date(<?php echo $phpTimestamp; ?> * 1000);
or
jsTimestamp = new Date(<?php echo strtotime($yourDateString); ?> * 1000);
Note that new Date(...) also accepts strings, see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date for more details.

Using PHP inside a JavaScript function

I'm using the jQuery countdown plugin to have a timer on my website
http://keith-wood.name/countdownRef.html
I am using an API from SportsRadar to list some fixtures that has the dates on
<?php echo date("Y/d/m/ - H:i", strtotime($nextMatch['KickOff'])); ?>
this will output as 23/04/2015 - 20:00
In the Countdown plugin their function is the following
<script>
var matchDay = new Date();
matchDay = new Date(2015, 04-1, 22, 20, 0, 0);
</script>
I'm just looking to know how would I add that PHP echo into that JavaScript function? Is it even possible?
You an use something like:
var matchDay = new Date(<?php $time = strtotime($nextMatch['KickOff']);
echo date("Y", $time) . "," . date("m", $time) . "," .
date("m", $time) . "," . date("H", $time) . "," .
date("i", $time);
?>, 0, 0);
Or you an parse date in JavaScript
PHP function strtotime() gives you the number of seconds since 1970. You can use this information to initialize a javascript Date object. However, javascript expects the number of milliseconds since 1970, thus you ought to multiply the value by 1000:
<script>
var matchDay = new Date(<?php echo strtotime($nextMatch['KickOff'])*1000;?>);
</script>
Now you know when the match will take place (in javascript), and you can use it to initialize a countdown or whatever else you want to do with this information.
PHP is server-side and will run once. JS is much unlike this. If you need the JS to call a PHP script, consider making an AJAX call. Looking at your goals, however, this seems a tad unnecessary. If all you want is to echo data, you can use JS to update HTML elements on the page instead. That I believe would be the simple solution for your requirements.
By doing this it worked fine
<script>
var matchDay = new Date();
matchDay = new Date('<?php echo date("Y", strtotime($nextMatch['KickOff'])); ?>', '<?php echo date("m", strtotime($nextMatch['KickOff'])); ?>'-1, '<?php echo date("d", strtotime($nextMatch['KickOff'])); ?>', '<?php echo date("H", strtotime($nextMatch['KickOff'])); ?>','<?php echo date("i", strtotime($nextMatch['KickOff'])); ?>');
</script>

Is it possible to refresh a DIV without another page inside the DIV?

as the title says, is it possible to refresh a div without another html or php page inside of the div?
for example this is what can be done using javascript:
$(document).ready(function () {
$('#mydiv').delay(10000).load('page.php');
});
My Div shows/holds a data which is pulled from the mysql database and it doesn't have page.php inside it.
I've searched for this and all the results were similar to the one i posted above!
is this even possible and if so how?
EDIT:
the data that currently is displayed in the DIV is the $end_time for an item. the $end_time is basically a datetime which is stored in the mysql database. the $end_time already is ticking (a countdown timer using javascript). There is button which whenever pressed, 1 minute Will be added to the $end_time in the mysql.
But when the button is pressed I need to refresh/re-load the page in order to be able to view the changes (in this case 1 minuted added to the countdown timer).
what I need to do is to reload the DIV once that button is pressed so all the users can see that 1 minute has been added to the countdown timer WITHOUT reloading or refreshing the page.
EDIT:
Here is my full code, this works as it should and it will pull the data from mysql database as it should so I have no problem with this part of the project:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php date_default_timezone_set('Europe/London'); ?>
<?php
session_start();
// Run a select query to get my letest 6 items
// Connect to the MySQL database
include "config/connect.php";
$dynamicList = "";
$sql = "SELECT * FROM item ORDER BY id";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$product_name = $row["product_name"];
$date_added = date("Y-m-d", strtotime($row["date_added"]));
$end_date = date("F d Y H:i:s T", strtotime($row["end_date"]));
$price = $row["price"];
$dynamicList .= '<div>' . $end_date . '
</div>';
}
} else {
$dynamicList = "No Records";
}
?>
<?php
$date = $end_date;
$exp_date = strtotime($date);
$now = time();
if ($now < $exp_date ) {
?>
<script>
// Count down milliseconds = server_end - server_now = client_end - client_now
var server_end = <?php echo $exp_date; ?> * 1000;
var server_now = <?php echo time(); ?> * 1000;
var client_now = new Date().getTime();
var end = server_end - server_now + client_now; // this is the real end time
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour *24
var timer;
function showRemaining()
{
var now = new Date();
var distance = end - now;
if (distance < 0 ) {
clearInterval( timer );
document.getElementById('countdown').innerHTML = 'EXPIRED!';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor( (distance % _day ) / _hour );
var minutes = Math.floor( (distance % _hour) / _minute );
var seconds = Math.floor( (distance % _minute) / _second );
var countdown = document.getElementById('countdown');
countdown.innerHTML = '';
if (days) {
countdown.innerHTML += 'Days: ' + days + '<br />';
}
countdown.innerHTML += 'Hours: ' + hours+ '<br />';
countdown.innerHTML += 'Minutes: ' + minutes+ '<br />';
countdown.innerHTML += 'Seconds: ' + seconds+ '<br />';
}
timer = setInterval(showRemaining, 1000);
</script>
<?php
} else {
echo "Times Up";
}
?>
<div id="result"><div id="countdown"></div></div>
<?php echo $end_date; ?> </br>
<?php echo $dynamicList; ?>
<script src="ajax_link.js" type="text/javascript"></script>
<div id="ajaxlink" onclick="loadurl('timeadder.php')">Click here</div>
<input type="submit" name="ajaxlink" id="ajaxlink" value="Submit" onclick="loadurl('timeadder.php')"/>
and Here is the code for the page that will add the 1 minute to the database and this owrks fie as it should too:
timeadder.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php
session_start();
// Run a select query to get my letest 6 items
// Connect to the MySQL database
include "config/connect.php";
$sql = "UPDATE item SET end_date = DATE_ADD(end_date,INTERVAL 1 MINUTE) WHERE id = 1;";
$query = mysqli_query($db_conx, $sql);
?>
All i need to do is to refresh the DIV countdown that holds the timer.
I hope someone now can help.
The question is unclear, but if your were trying to periodically load a php into a div it could be done with setInterval
setInterval(
function(){
$('#mydiv').load('page.php');
},10000);
EDIT:
Ok then Id suggest Jquery.get
setInterval(function(){
$.get('page.php',function(timerValue){
$('#mydiv').html(timerValue);
});
},1000);
Modified to integrate newly posted code in OP:
In your while{} statement, you are sticking div tags around the end date, but there is no easy way to identify which item's end date the div belongs to.
Suggestion:
$dynamicList .= '<div id="ed-' .$id. '">' . $end_date . '</div>';
That will create a uniquely named div around each end date. Now, you can access a specific end date via jQuery, thus:
$('#ed-3').html(newdata);
Also, shouldn't this:
<div id="result"><div id="countdown"></div></div>
<?php echo $end_date; ?> </br>
Be like this:
<div id="result"><div id="countdown"><?php echo $end_date; ?></div></div>
</br>
HTML:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var item_id = 0;
$(document).ready(function() {
$('#mybutt').click(function() {
item_id = $(this).attr('id').split('-')[1];
updateTimer();
});
}); //END $(document).ready()
function updateTimer() {
$.ajax({
type: 'POST',
url: 'getenddate.php`,
data: `item=` + item_id,
success: function(fromPhp) {
$('#countdown').html(fromPhp);
//or, to change this item's end date as echoed out from $dynamicList:
//$('#ed-' + item_id).html(fromPHP);
} //END success fn
}); //END AJAX code block
adder = 0;
} //END updateTimer fn
</script>
</head>
<body>
<div id="countdown"></div>
<input id="item-12" type="button" value="Add One Minute">
</body>
</html>
PHP: getenddate.php
<?php
//item is NAME of var being posted over (key),
//item_id is the var contents on the client side ONLY
//$_POST['item'] is var contents (value) as it arrives on PHP side
$itemid = $_POST['item'];
// ** FIXME the query contains a SQL injection vuln,
// ** please untaint $itemid before using
//code to return current time value from database - runs every time
$end = mysql_result(mysql_query("SELECT `end_date` FROM item WHERE `id` = '$item' "), 0);
echo $end;
If I understood you right, you want to change the content of a DIV, no matter what is inside. This can be accomplished like this:
in the HTML you have something like:
<div id="mydiv">My old content, no sites here</div>
An in the JS(jQuery enabled) you do (for example in the ready function):
$(document).ready(function () {
$('#mydiv').html("This content is brand new");
});
jsFiddle of the code above
The .html() function deletes the old content of that tag and replaces it with new content.
If you, for example, want to show the current seconds, you can do as follows:
$(document).ready(function () {
setInterval(function(){
// change time
$('#mydiv').html("Seconds: "+ new Date().getSeconds());
},1000);
});
jsFiddle of the code with counter
This should be almost exactly what you are looking for (untested):
HTML:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var adder = 0; //Global var -- outside document.ready
$(document).ready(function() {
$('#mybutt').click(function() {
adder++;
updateTimer();
});
}); //END $(document).ready()
function updateTimer() {
$.ajax({
type: 'POST',
url: 'myphpprocessor.php',
data: 'addval=' + adder,
success: function(fromPhp) {
$('#theTimer').html(fromPhp);
} //END success fn
}); //END AJAX code block
adder = 0;
} //END updateTimer fn
</script>
</head>
<body>
<div id="theTimer"></div>
<input id="mybutt" type="button" value="Add One Minute">
</body>
</html>
PHP: myphpprocessor.php
<?php
$howmuch = $_POST['addval'];
if ($howmuch > 0) {
//code to update database by the amount
// - only runs if howmuch has a value
}
//code to return current time value from database - runs every time
$thetime = mysql_query('SELECT etc etc etc');
echo $thetime;
Notes:
The database only needs to store the number of minutes to be added to the current time
Your PHP code can then:
(a) Query the DB for number of mins to add: $num_mins_to_add
(b) Create a new date object with current time
(c) Add the $num_mins_to_add to (b)
(d) ECHO back the value

Categories

Resources