Turn php countdown into javascript - javascript

On my php website I have many various countdowns. These are only updated when the user refreshes the page. I want to change it so that the countdown is continous.
I have found many javascript codes that perform this, however I'm unsure how to implement my php code into there script.
Please see below scripts:
My php function for timer:
function countup ($online){
global $time;
$difference=$online-$time;
$num = $difference/86400;
$days = intval($num);
$num2 = ($num - $days)*24;
$hours = intval($num2);
$num3 = ($num2 - $hours)*60;
$mins = intval($num3);
$num4 = ($num3 - $mins)*60;
$secs = intval($num4);
if($days != 0){echo"$days days, ";}
if($hours != 0){echo"$hours hours, ";}
if($mins != 0){echo"$mins minutes and ";}
echo"$secs seconds";
}
where I show the timer I have the following.. <?=countup($set[ends])?>
Ends = future unix timestamp.
The javascript countdown I came across was from http://keith-wood.name/countdown.html but I have no understanding of java and am not sure how to put $set[ends] into it!
All help would be greatly appreciated!

Considering, that you're loading all required scripts properly, here is what I would suggest:
PHP part
$ends = date("Y, n-1, j", $set[ends]); //covert your time stamp to the required format
**JavaScript Part **
<script type='text/javascript'>
( function( $ ) {
$('#yourCountDownDIV').countdown({until: <?php echo $ends ?>});
} )( jQuery );
</script>
Put the JavaScript part at the end of the HTML code just before the closing tag and after all your JavaScript files are loaded.

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", ...

How to invoke the function in javascript based on condition

i am trying to send an auto generated mail for wedding event so i have an countdown timer using java script and i want to send a reminder before a day . i tried in php and java script but i am not getting expected output.
Tried below code using java script, but it is not sending /displaying my message on the console
<!DOCTYPE html>
<html>
<p id="demo"></p>
<style>
p {
text-align: center;
color: #7FFF00;
font-size: 50px;
margin-top: 0px;
}
</style>
<script>
// Set the date we're counting down to
var countDownDate = new Date("April 3, 2019 10:30:01").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 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 = "Today is the wedding";
}
var myvar=20;
while(distance==myvar){
document.getElementById("demo").innerHTML = "Reminder";
<?php
//to send an wedding reminder
include "Sendmail.php"
?>
}
}, 1000);
</script>
</html>
Hence i tried with below Php using page auto refresh option:but it is not working as exected-------------------------------------------------------------------------------
<!DOCTYPE html>
<html>
<body>
<?php
echo "Today is " . date("l");
//date_default_timezone_set('America/New_York');
//timezone_name_from_abbr('IHST',19800) for Asia/Colombo
//set the timezone for ist:
date_default_timezone_set('Asia/Kolkata');
$today = date("Y-m-d H:i:s");
$date = "2019-02-26 07:43:16 ";
$tilldate = "2019-02-26 07:43:50 ";
echo $today;
do {
$page = $_SERVER['PHP_SELF'];
$sec = "6";
//echo "Watch the page reload itself in 3 second!";
}while ( $date<=$today)
echo" when satisfied call my function and come out of loop";
break;
//if($today < $date ||$today < $tilldate){
//echo "Watch the page reload itself in 3 second!";
//break;
// echo "Watch the page reload itself in 3 second!";
//include 'FetchData.php';
//}
?>
<html>
<head>
<meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">
</head>
<body>
<?php
echo "Watch the page reload itself in six second!";
?>
</html>
It will be very helpful if some one assist me on this.
If your goal is to build a site where people can enter a wedding date, and have it email them a reminder a set time before, you will need to store that data on a server somehow.
If you are familiar with NodeJS you could use it to set up a small app that keeps the wedding dates in memory, (though longer-term storage is safer), and then you can use something like Nodemailer to send the email once the time is reached.
However if you don't know NodeJS, using Javascript alone won't be enough - and you can't call PHP code with JS using an embed like you're doing. Keep in mind that PHP is rendered out before any Javascript is run, so JS can't directly call a PHP function. In order to get JS to communicate with PHP in most cases you'll want to make an AJAX call to a PHP script on your server.
So your front end will be a page that uses JS to send an AJAX request containing a wedding date to a separate PHP script on your server. That PHP script will then save that data to the server, using something like mySQL, (or in a pinch you can just use fwrite( ) to write to the local file structure, though a full database system is safer.)
Now you'll need a 2nd PHP script that checks the data every minute or so, and sends an email when a wedding date is close enough. However, you don't want to use auto-refresh to keep a PHP script running. Instead you'll want to set up a cron task that calls your PHP script however often you need it to.
So the elements you'll need are: 1) HTML page containing Javascript, which sends AJAX data to 2) A PHP script that saves that data to your server, and 3) A 2nd PHP script, called by cron, which checks the data and emails when necessary
On the other hand, if all you need is an email reminder for one specific wedding, you'd probably be better off scheduling it through your email client, or using something like IFTTT.

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 add a progress bar to script that downloads file from url to server

I have searched for a script that download files from url to server and I came across this script. It works fine but I want to add some things to it like multi urls and progress bar. As I am new in php I know a little .
Here is the script in which I want to implement:
<html>
<form method="post">
<input name="url" size="50" />
<input name="submit" type="submit" />
</form>
<?php
// maximum execution time in seconds
set_time_limit (24 * 60 * 60);
if (!isset($_POST['submit'])) die();
// folder to save downloaded files to. must end with slash
$destination_folder = 'downloads/';
$url = $_POST['url'];
$newfname = $destination_folder . basename($url);
$file = fopen ($url, "rb");
if ($file) {
$newf = fopen ($newfname, "wb");
if ($newf)
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
?>
</html>
For the multiple links you can tell the user to input all links seperated with commas. Then you could create an array with these links (using explode function) and loop over it until you download all files from the links. The code is below:
<html>
<form method="post">
<input name="url" size="50" />
<input name="submit" type="submit" />
</form>
<?php
// maximum execution time in seconds
set_time_limit (24 * 60 * 60);
if (!isset($_POST['submit'])) die();
// folder to save downloaded files to. must end with slash
$destination_folder = 'downloads/';
$urls = $_POST['url']; // I changed this variable's name to urls
$links = explode(",",$urls); // links is now an array with the links
foreach ($links as $url)
{
$newfname = $destination_folder . basename($url);
$file = fopen ($url, "rb");
if ($file) {
$newf = fopen ($newfname, "wb");
if ($newf)
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
}
?>
Useful links:
Explode: http://php.net/manual/en/function.explode.php
Foreach: http://php.net/manual/en/control-structures.foreach.php
If you want to have another input box appear you would have to use javascript and it is a bit complicated. But if you want, I can show you that way too.
For the progress bar, you will need javascript and css Bootstrap. I am trying to create a code that does what you want. When and if i manage to do so, I will upload it here, so you might want to come back later and check it out.
Since you want to have the ability to show new input boxes here is the code:
<html>
<form method="post">
<input type="text" id="input1" name="input1" size="50" />
<div id="new"></div>
<br><input type="button" value="+" onclick="writeBtn();"><br><br>
<input name="submit" value="Download" type="submit" />
</form>
<script type="text/javascript">
url_id=1;
function writeBtn()
{
if (document.getElementById("input"+url_id).value != "")
{
url_id++;
var input = document.createElement("input");
input.type="text";
input.id="input"+url_id;
input.name="input"+url_id;
input.size="50";
input.required=true;
var br1 = document.createElement("br");
var br2 = document.createElement("br");
setTimeout(function(){
$(input).click();
},200);
document.getElementById('new').appendChild(br1);
document.getElementById('new').appendChild(input);
document.getElementById('new').appendChild(br2);
}
else
{
alert("Please complete the last url first.");
}
}
</script>
<?php
// i have just added this maximum execution time in seconds
set_time_limit (0);
function downloadFromUrl($url, $destination)
{
$newfname = $destination . basename($url);
$file = #fopen ($url, "rb");
if ($file)
{
$newf = fopen ($newfname, "wb");
if ($newf)
while(!feof($file))
{
fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
}
// and replaced this with if command
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
return true;
}
else
{
return false;
}
}
if (!isset($_POST['submit'])) die();
// folder to save downloaded files to. must end with slash
$destination_folder = 'downloads/';
for ($i=1; isset($_POST["input".$i]); $i++)
{
$url = $_POST["input".$i];
if(downloadFromUrl($url, $destination_folder))
echo "<br>Succesfully Downloaded from: ".$url;
else
echo "<br>Error Downloading from: ".$url;
}
?>
Explanation:
In the html form there is a div with id="new". In this div is where an input box is dynamically added when the button with the + sign is clicked. If you want to learn more about how this is achieved you can visit this link: http://www.w3schools.com/jsref/met_document_createelement.asp. The values from input boxes are afetrwards accessed by their names, which are input1, input2 etc. For this dynamic name giving the variable url_id is used in javascript part and is increased for every new input box. Also there is a feature I added, which doesn't allow user to create new input if the last one is empty and alerts a message. The if statement for this is:
if (document.getElementById("input"+url_id).value != "")
so, if you don't want this just delete this line and the else block. I also included your code for downloading in the function downloadFromUrl for simplicity reasons, which returns true if file was succesfully downloaded and false otherwise. In the php part there is a for loop that parses all inputs downloads the file that is in the url and echos a message if it was or not succesfully downloaded by calling the function downloadFromUrl.
As for your other question about the progress bar, I spent like the whole day trying to find a solution. Long story short, I wasn't able to make it work and I think it can't possibly work. I will explain you why. From php we can't change the value of the progress bar because php is executed and then prints all the results on screen, so we will only have the last change of the progress bar which will always be 100%. The other way is to use javascript. In that case we have to download the files from javascript because if we download them from php, by the time javascript starts executing, the files will have already been downloaded from php. Even if we execute a php script from javascript that downloads the files , we won't be able to tell when a file is downloaded, so we can't update the progress bar at the right time. So what is left? Downloading the files from javascript using XMLHttpRequest, which can't be achieved for 2 reasons. First, browsers don't allow this for security reasons and second and most important you can't upload the file to the server from javascript because javascript is a client-side language and doesn't have access to the server.
As you can see I tried many ways. If someone finds a way to do this, please let me know. I hope I helped you with your project. For any questions, problems, errors on the first half of the answer and suggestions or corrections for the second part of the answer are very welcome.
For the progress bar, I have already spent some time. There are two ways. Storing the total size of the remote file in a txt/Database file then compare each time. Or you can use AJAX at realtime. Hope if anyone can apply these ideas would share.

CountDown Timer Before Redirect In Pure PHP

I am using a pure JavaScript count down timer that I shared below to redirect to a URL after some time and show the left time to visitor also.
DEMO: JSFiddle
<form name="redirect" id="redirect">
You Will Be Redirected To Next Page After <input size="1" name="redirect2" id="counter"></input>Seconds.
</form>
<script type="text/javascript">
var countdownfrom=5
var currentsecond=document.redirect.redirect2.value=countdownfrom+1
function countredirect(){
if (currentsecond!=0){
currentsecond-=1
document.redirect.redirect2.value=currentsecond
}
else{
showIt()
return
}
setTimeout("countredirect()",1000)
}
countredirect()
function showIt() {
window.location.href = "http://jsfiddle.net/";
}
</script>
Now I want the same function and features and work in pure PHP as you know that many old mobile browsers still does't not support JavaScript and many are using JavaScript blocker. So Is this possible to do the same in Pure PHP, no <script> tags.
UPDATE:
I know the below codes but I want a count down timer too to show to the visitor.
<?php header('Refresh: 5; URL=http://jsfiddle.net/'); ?>
<meta http-equiv="refresh" content="5;url=http://jsfiddle.net/">
Answer:
This can't be done only with php you will need to use jquery or javascript with it. PHP is a server side scripting language you have to use client side language for this task.
Tip:
For redirecting purpose Just use header() function in php to redirect the php file in some time.Your code should look like this
<?php
header( "refresh:5;url=http://jsfiddle.net" );
?>
Hope this helps you...
Well if you want some output, you can't use header(). Alternatively, you could do something like this:
echo "<pre>";
echo "Loading ...";
ob_flush();
flush();
$x = 0;
while($x <= 4) {
$x++;
echo '<br/>'. $x;
ob_flush();
flush();
sleep(1);
}
echo '<meta http-equiv="refresh" content="0;url=http://jsfiddle.net/">';
PHP is a server-side language. You cannot control how the browser behaves from PHP without some quite complex setup. And even that, you cannot guarantee the behaviour of showing a countdown without JavaScript. For browsers who restrict JavaScript execution, the Refresh header will work just fine. However, for those having JavaScript enabled (which is the majority of browsers nowadays, desktop and mobile alike), a simple header will not give any UI feedback and is frustrating for users who expect responsive applications and web pages.
For this reason, JavaScript can be added, if available, to enhance the automatic, delayed, redirection and give the user some feedback of what's going on. Those with JavaScript disabled will just see a static page, telling them that the page will be redirected, and how long they have to wait for it.
PHP
<?php
$redirectTimeout = 5; // seconds
header('Refresh:' . $redirectTimeout . ';url=http://jsfiddle.net');
// ...
// inside your <head>, add this
echo '<meta http-equiv="refresh" ' .
'content="' . $redirectTimeout . ';url=http://jsfiddle.net">';
// ...
// inside your <body>, add this (or something similar)
echo '<div>' .
'You will be redirected to next page after ' .
'<span id="redirectCountdownLabel">' .
$redirectTimeout .
'</span> seconds' .
'</div>';
// ...
// add JS below
JavaScript
For this part, I recommend you use jQuery. It will not only write safer and cross-browser JS, it will also make your code smaller and prettier. This part can be put anywhere in your HTML, or inside a .js file that you add with a <script> tag. For convenience, you can even add jQuery using a CDN.
!function() {
$(function () {
var meta = $('head meta[http-equiv="refresh"]');
var label = $('#redirectCountdownLabel');
var loadTime;
var refreshTimeout;
if (meta.length && label.length) {
loadTime = window.performance.timing.domComplete;
refreshTimeout = parseInt(meta.attr('content'), 10); // seconds
new Timer(refreshTimeout * 1000, loadTime).start(200, function (elapsed) {
// "elapsed" ms / 1000 = sec
label.text(refreshTimeout - parseInt(elapsed / 1000));
});
}
});
function Timer(maxTime, startTime) {
var timeout;
var callback;
startTime = startTime || Date.now();
function nextTimer(delay) {
timeout = setTimeout(function () {
var curTime = Date.now();
var elapsedTime = curTime - startTime;
callback(elapsedTime);
if (elapsedTime < maxTime) {
nextTimer(delay);
}
}, delay);
}
this.start = function start(ms, cb) {
stop();
callback = cb;
nextTimer(ms);
};
this.stop = function stop() {
if (timeout) {
clearTimeout(timeout);
}
};
};
}();
(Note: here's a jsfiddle of the Timer class.)
scusate per prima, ho postato male, sono ali inizi, sorry
<?php
echo "<pre>";
echo "Loading ...";
ob_flush();
flush();
$x = 21;
while($x >= 1) {
$x--;
echo '<br/>'. $x;
ob_flush();
flush();
sleep(1);
}
echo '<meta http-equiv="refresh" content="0;url=http://jsfiddle.net/">';
To do the countdown, so it seems to work or am I wrong?
<?php
echo "Loading ...";
ob_flush();
flush();
$x = 21;
while($x >= 1) {
$x--;
echo '<br/>'. $x;
ob_flush();
flush();
sleep(1);
}
echo '<meta http-equiv="refresh"content="0;url=http://jsfiddle.net/">';
?>`

Categories

Resources