Sorry for poor title.
I basically want to start a countdown (5 minutes) if a certain thing reports back witha number. Most of the backend is in PHP but I want to animate to the countdown so the user can see (maybe even with a progress bar eventually). But once the countdown his zero, if the condition is not met I want it to, lets say refresh the page for simplicity.
I'm looking for some guidance in right guidance. Should I:
Run timers seperately in JS and PHP
or
Do something like this Countdown timer built on PHP and jQuery? with a common php file included or something along those lines
Thanks guys.
well if you want a timer triggered by something that reports to the backend when it its over you could just do an ajax request with JQuery. I will try to explain it based on the condition that PHP has to init the counter as you show to us at the example timer.
Add JQuery to your project Download it here
Download JQuery countdown here, also you can read more about the library here
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="./jquery.countdown-2.2.0/jquery.countdown.min.js"></script>
</head>
<body>
<div class="countdown">
<span id="clock"></span>
</div>
<script>
function initTimer()
{
<?php
date_default_timezone_set('America/Bogota'); //Your target timezone
$time = new DateTime();
$minutes_to_add = 5;
$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));
?>
$('#clock').countdown('<?php echo $time->format('Y-m-d H:i:s'); ?>')//so we init the timer at te server time + 5 minutes
.on('update.countdown', function(event) {
var format = '%H:%M:%S';
$(this).html(event.strftime(format));
})
.on('finish.countdown', function(event) {
$(this).html('This offer has expired!')
.parent().addClass('disabled');
//at the end of the timer we will send data to the server
$.ajax({
url: "your_server_service_url",
method: "GET",
data: {"some":"data you want to sent to server"}
}).done(function(r){ // r is the response from your server (all text printed)
location.reload(); //After the server get the data we reload the current page.
});
});
}
initTimer();
</script>
</body>
</html>
Related
I'm running website on the local server at (http://127.0.0.1:8080).
I have a file named track located at api/track where api is simply a folder.
I have a file name main.js located at js/main.js.
Finally, I have my index.html file located at the same level with /api and /js.
I would like to make a network call to this endpoint (api/track) each time a page index.html loads.
Also, I'd like to include a timestamp ts (in milliseconds since EPOCH). An Example of the url would be /api/track?ts=1594280202864. I don't need to use the results of this call.
Here is what I did, but I'm not sure it's doing what I want especially the network call part. Can somebody help, please? Thanks
const update = () => {
var dt = new Date();
document.getElementById("date").innerHTML = dt;
//date in millisecodn since EPOCH
var dtInMilSec = dt.getTime();
fetch('/api/track/dtMilSec')
.then(response => response.json())
.then(data => {
console.log(data)
});
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>The Date</title>
<link href="style/main.css" rel="stylesheet" />
</head>
<body onload="update()">
<h1>What's today's date?</h1>
<p>Today is: <span id="date"></span></p>
<script src="js/main.js"></script>
</body>
https://stackoverflow.com/a/25984032/14649968
Maybe take a look at this answer on a related thread, and call your update() function from within the event listener for DOMContentLoaded within the main.js script, rather calling it from the onload attr in the html itself?
document.addEventListener('DOMContentLoaded', () => update(), false);
Seems like you want your fetch URL to be something like
fetch('/api/track?ts=' + dtInMilSec)
Hi everyone!
I've made a MySQL database that contains the state of a minecraft lever using the ComputerCraft mod and some javascript but here is the problem : it's too slow :/So I would like to know if there isn't a simpler / quicker way to do it '\(*-*)/`
Here are the steps I went through :1-I've set a computer in my minecraft world with this startup program :
ecran = peripheral.find("monitor")
term.redirect(ecran)
while true do
term.clear()
local h = fs.open("test","w")
print(os.version())
print(rs.getInput("right"))
text = "etatBout = '"..tostring(rs.getInput("right")).."'"
h.write(text)
h.close()
os.sleep(0.5)
term.setCursorPos(1,1)
end
so that the computer write the state of the lever in the file 'test'2-I've created a index.html file in the same folder :
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>TestMCJS</title>
<meta http-equiv="refresh" content="0.5" />
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="test"></script>
<script type="text/javascript">
console.log(etatBout)
if(etatBout=='true'){
window.open('http://192.168.1.47/minecraft/index.php?etatbouton=1', 'jeux');
}else if(etatBout=='false'){
window.open('http://192.168.1.47/minecraft/index.php?etatbouton=0', 'jeux');
}
</script>
</head>
<body>
<h1>Test</h1>
<p></p>
</body>
so it send a php request to a lamp server I run on a virtual machine with the state of the button in parameter3-I've created the index.php with the following code:
<!DOCTYPE html>
<head>
</head>
<body>
<?php
$connexion = new mysqli("localhost","chuck","plouf","mc");
$requete = $connexion->query("INSERT into `etatbouton` (etat) VALUES ('".$_GET['etatbouton']."')");
$requete->close();
$connexion->close();
?>
</body>
Then the state of the button is in my database in the 'etat' column and is related to a 'date' column with the current_timestamp as default value4-Now I just have to read the database in index2.php :
<!DOCTYPE html>
<head>
<meta http-equiv="refresh" content="0.5"/>
</head>
<body>
<?php
$connexion = new mysqli("localhost","chuck","plouf","mc");
$requete = $connexion->query("SELECT `etat` FROM `etatbouton` ORDER BY `date` DESC LIMIT 1");
$ligne = $requete->fetch_assoc();
if($ligne['etat']!= 0){
echo("<h1 style='font-size:5em;color:blue'>ON</h1>");
}else{
echo("<h1 style='font-size:5em;color:red'>OFF</h1>");
}
$requete->close();
$connexion->close();
?>
</body>
And that's it.
I'm proud of me because I'm a newbie but I would like to know if there is a simpler or quicker way to do it because with this set I have to open 3 tabs and one is a pop-up so it is blocked by the browser and it takes approximetly 1 or 2 seconds to update the button state in the browser :/
Hi again
Appenrently I could use LOAD DATA in my first page to avoid the pop-up and make it quicker so thank you.
Bye Bye ,(°0°)/
So i have a problem. A made a chat with php and mysql. But, if I enter a text, I can't see it in the other window because it is not updating. So I started to make a program with iframe, and i found it much cooler than the other. I'm using to reload the frame all 2 seconds. Now my question is, how can I make this easier with javascript, so that the chat is updating automatically?
Code of the frame (I'm german, so it's a little bit confusing):
<?php
require 'config.php';
session_start();
?><head><link href="https://fonts.googleapis.com/css? family=Source+Sans+Pro:300,400,700" rel="stylesheet">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Studit</title><link rel="stylesheet" href="lobby.css"><meta http-equiv="refresh" content="5; URL=/ownwebsite/lobby1embed.php"></head><?php
$abfrage = "SELECT * FROM lobby1 ORDER BY id DESC";
$abfrage_antwort=mysqli_query($con, $abfrage);
if (!$abfrage_antwort)
{
die('Ungültige Abfrage:' .mysqli_error());
}
echo '<table border="1">';
while ($zeile = mysqli_fetch_array($abfrage_antwort, MYSQLI_ASSOC))
{ //row algorithm...}
You can use setInterval (functionRefreshingChat, 1000); in javascript.
It'll create infinite loop with delay 1000ms.
According to one of comments to your question: setTimeout is not solution. It'll execute inner function only once.
I want to refresh an HTML page every hour automatically in the background. I was thinking about using PHP but I'm not sure what if that's possible.
This is all the I have:
<meta http-equiv="refresh" content="3600" >
But this doesn't refresh automatically in the background. How can I do this? If this is possible in PHP and a cron job please let me know (with code preferably). Thank you.
You can use javascript setInterval();
<script>
$(document).ready(function(){
setInterval(function(){ reload_page(); },60*60000);
});
function reload_page()
{
window.location.reload(true);
}
</script>
Try this :
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "3600";
?>
<html>
<head>
<meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">
Refer to this answer https://stackoverflow.com/a/19807718/6390490
Refresh document every 300 seconds using HTML Meta tag
EDIT: for background you have to use ajax something like this https://stackoverflow.com/a/25446696/6390490
function loadlink(){
$('#links').load('test.php',function () {
$(this).unwrap();
});
}
loadlink(); // This will run on page load
setInterval(function(){
loadlink() // this will run after every 5 seconds
}, 5000);
for server side refreshing use
header("Refresh: 300;url='http://thepage.com/example'");//set time here as per your need
In JavaScript it is possible to wait for onLoad which may be used to specify the time of page loading completion.
Every HTTP response is sent along with Date: header which contains the time server sent a response.
Is there a way in JavaScript to get the time of page started loading?
Something similar to response Date: header.
It would be useful for cases when JavaScript is injected into page after some delay.
new Date(performance.timing.connectStart) in chrome, firefox, IE9, etc (caniuse)
demo
console.log(new Date(performance.timing.connectStart));
Try storing a value from var d= new Date(); var requested = d.getTime(); and execute it when the page loads.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var loadDate;
</script>
</head>
<body onload="loadDate=new Date();">
<button onclick="alert(loadDate);">show load Date</button>
</body>
</html>
I would just pass a timestamp from the server-side script to the browser via a cookie or inline JS. E.g. in PHP:
<script>
var timestamp = new Date(<?php echo time(); ?>);
</script>