I wish to show the current local time on my weather web site.
This is the code that I use from a query :"Automatically update time in PHP using Ajax" posted 2 years ago
<?php
echo "<html>
<head>
<title>Realtime clock</title>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<script src='http://code.jquery.com/jquery.js'></script>
<script>
$(document).ready(function(){
setInterval(_initTimer, 1000);
});
function _initTimer(){
$.ajax({
url: 'timer.php',
success: function(data) {
console.log(data);
data = data.split(':');
$('#hrs').html(data[0]);
$('#mins').html(data[1]);
$('#secs').html(data[2]);
}
});
}
</script>
</head>
<body>
<span id='hrs'>0</span>:<span id='mins'>0</span>:<span id='secs'>0</span>
</body>
</html>"; ?>
<?php date_default_timezone_set("Australia/Brisbane");
echo "Current Time: ". date("H:i:s"). " AEST";
?>
This is what I getwhen I run this:
17:05:10 Current Time: 17:01:30 AEST
What I am aiming to achieve is:
Current Time: 17:05:10 AEST with the time updating every second.
Is there some addition that I need to make in the final echo statement? Or do something else
please help
Thanks
To show current time every second you could use jquery to show time, instead of running ajax on server for every second
Try this:
var nIntervId;
function updateTime() {
nIntervId = setInterval(flashTime, 1000);
}
function pad(n) { return ("0" + n).slice(-2); }
Number.prototype.pad = function (len) {
return (new Array(len+1).join("0") + this).slice(-len);
}
function flashTime() {
var now = new Date();
var h = now.getHours().pad(2);
var m = now.getMinutes().pad(2);
var s = now.getSeconds().pad(2);
var time = h + ' : ' + m + ' : ' + s;
$('#my_box1').html(time);
}
$(function() {
updateTime();
});
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<div id="my_box1">
</div>
I assume you have made a separate timer.php file just to echo server time. As your current page is loading just once, the initial server time will not be updated that is your "current time value". Whereas the remaining DOM will be updated with the server time because of ajax code. If you want both times to be same you will have to reload the whole page which is not correct. Hence, I suggest you to display only one time which should be your ajax result.
timer.php:
<?php
date_default_timezone_set("Australia/Brisbane");
echo date("H:i:s");
?>
Related
I am needing to automatically refresh my PHP page. I have a PHP page that is returning the current database time. However, this is requiring me to refresh the page in order for me to update.I need a better way of updating this PHP variable that does not include refreshing the page. Here's what I have so far:
$time = current_time($db);
echo '<p>$time</p>'
How can I accomplish this?
EDIT:
I've changed my code but it still won't auto-refresh:
index.php
<div id="#timeLocation">
<script>
var updateTime = function(){
$.ajax({url: "time.php", success: function(response){
$('#timeLocation').html(response);
}});
setInterval(updateTime, 1000);
}
updateTime();
</script>
</div>
time.php
<?php
require_once('db.php');
require_once('functions.php');
$time = current_time($db);
echo $time[0];
?>
index
<html>
<head>
<meta charset="UTF-8">
<title>Time</title>
</head>
<body>
<div id="time">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
setInterval(function(){
$.ajax({url: "time.php", success: function(response){
$('#time').html(response)
}});
}, 1000);
</script>
</body>
</html>
time.php
<?php
$time = date("g:i:s a");
echo $time;
this isnt the exact answer but it will help you along the way, watch when using ajax the way ive displayed though, sending a request everysecond could eventually slow down your server with enough time
With javascript you can run a function every tot. second:
setInterval(function,60000)
The function that you call should be an ajax request to a PHP page, that return the current hour. In my opinion you can implement all with only javascript, calling a function every second that update the hour field.
While ajax has been told in the comments, here is a pseudo implementation of it:
<div id="#timeLocation"></div>
<script>
const updateTime = function(){
$.ajax({url: "time.php", success: function(response){
$('#timeLocation').html(response);
}});
setInterval(updateTime, 1000);
}
updateTime();
</script>
This will update the timeLocation div with the content of time.php every second.
I wrote this php code to show server date and time but I'd like to display realtime change in server date and time every 1 Sec
<p><?php echo "Server Time " . date("Y-m-d h:i:s"); ?> (GMT) UTC +0 UK/London</p>
Pls help me, thank you
You will need to use Javascript, something like this:
<body>
<p id="time"></p>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
var timestamp = '<?=time();?>';
function updateTime(){
$('#time').html(Date(timestamp));
timestamp++;
}
$(function(){
setInterval(updateTime, 1000);
});
</script>
if you still need a real time clock that uses your server clock you could try this. im using twig {{now|date('Y/m/d H:i:s')}}. but you could also use php's <?php echo date('Y/m/d H:i:s');?>. its basically using localStorage to store the server date on localstorage and setSeconds updates the localstorage every 1 second , while the now variable loads the localstorage date and converts it to js date format. I then use the {{now|date('Y/m/d H:i:s')}} inside the date element for fallback in case localstorage is not enabled.
try {
localStorage.setItem('today', new Date("{{now|date('Y/m/d H:i:s')}}");
setInterval(function clock() {
var month = [
"Jan", "Feb", "Marh", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Octr", "Nov", "Dec"
];
var now = new Date(localStorage.getItem('today'));
now.setSeconds(now.getSeconds() + 1);
localStorage.setItem('today', now);
var G = format(now.getHours() % 12 || 12);
var i = format(now.getMinutes());
var s = format(now.getSeconds());
var M = month[now.getMonth()];
var d = format(now.getDate());
var Y = now.getFullYear();
function format(data) {
return (data < 10 ? data = "0" + data : data);
}
$("#date").html(M + ". " + d + ", " + Y + " " + G + ":" + i + ":" + s);
return clock;
}(), 1000);
} catch(e) {
console.log(e);
}
you can get server time when page loaded and use javascript function to update time locally persecond.
HTML PAGE
<script> var JS_BASE_URL = 'http://YOURSERVER/';</script>
<script src="assets/js/jquery-3.4.1.min.js" type="text/javascript"></script>
<script src="clock.js" type="text/javascript"></script>
</head>
<body>
Server Time <span id="server_time">00:00:00</span>
</body>
clock.js
var url = JS_BASE_URL+'/script.php';
var _h = 0;
var _m = 0;
var _s = 0;
$.ajax({
url: url,
type: 'GET',
dataType: 'JSON',
success: function(res) {
var timer = setInterval(serverTime,1000);
function serverTime(){
h = parseInt(res.hour)+_h;
m = parseInt(res.minute)+_m;
s = parseInt(res.second)+_s;
if (s>59){
s=s-60;
_s=_s-60;
}
if(s==59){
_m++;
}
if (m>59){
m=m-60;
_m=_m-60;
}
if(m==59&&s==59){
_h++;
}
_s++;
$('#server_time').html(append_zero(h)+':'+append_zero(m)+':'+append_zero(s)); }
function append_zero(n){
if(n<10){
return '0'+n;
}
else
return n;
}
}
});
script.php
<?php
$data = array('fulldate'=>date('d-m-Y H:i:s'),
'date'=>date('d'),
'month'=>date('m'),
'year'=>date('Y'),
'hour'=>date('H'),
'minute'=>date('i'),
'second'=>date('s')
);
echo json_encode($data);
?>
check on github: https://github.com/mdanielk/server_time
To display changing clock showing server time by using Ajax. Create two files for this one is the file sending request and receiving data with Ajax.
server-clock.php
develop a script where by clicking a button we can send a request to server to get the data. In the body of this file we have a button.
<input type=button value=
'Get Server Time' onclick="timer_function();">
To this script we will add a timer to recursively call the same Ajax function in every second. This will get data from every second so we can display a changing clock showing server time.
function timer_function(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('AjaxFunction();',refresh)
}
Timer function: timer_function()
On click of this button it trigger a function which uses a timer setTimeout. Inside this timer function it can change the refresh rate which is in milliseconds. Within this function we call our main Ajax function AjaxFunction()
function timer_function(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('AjaxFunction();',refresh)
}
At the end of AjaxFunction() call again timer_function() to make it recursive.
tt=timer_function();
In the main AjaxFunction() send request to clock.php file and get the server time. This data is displayed using a div layer.
if(httpxml.readyState==4)
{
document.getElementById("msg").innerHTML=httpxml.responseText;
document.getElementById("msg").style.background='#f1f1f1';
}
The second file is the simple PHP file with one line of code giving current date and time of server. clock.php
<?Php
echo date("d/m/y : H:i:s", time());
?>
download the files here
I would like to implement comet with records fetch from PHP
My PHP will do the following.. at a page call getlog.php
$sql = "select log_description,log_time from log ORDER by log_time DESC";
$result=mysql_query($sql);
if($result == false)
{ die("unable to fetch records."); }
while ($row = mysql_fetch_assoc($result)) {
$result_output[] = $row;
}
$counter = 1;
foreach($result_output as $row)
{
echo $counter . ". " $row[log_description];
$counter++;
}
If there is new log, I would want to echo it out in viewlog.php
So it would appear like this in viewlog.php
1. Customer 1 logged in at 12:05.
maybe 5 minutes later
1. Customer 2 logged in at 12:10
2. Customer 1 logged in at 12:05
It maintain a maximum of like lets say 15 records.
The data is fetch from PHP, I read the way to do it is something call "comet" but I just want a simple database fetch which auto refresh e.g every 10 seconds to see if there is new record added to the database and append it to the div.
Is there a easy way to achieve this using AJAX and PHP and not using comet.
Thanks for all the help, greatly appreciate !
Did the following code changes
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
show_log(){
var lnk = "fetchlog.php";
$.ajax({url:lnk,success:function(result){
$("#log_div").html(result);
}});
}
window.setInterval(function(){
show_log();
}, 10000);
</script>
</head>
<body>
<div id="log_div"></div>
</body>
</html>
Whats wrong with my code as it doesn't fetch from fetchlog.php
fetchlog.php echo something like this
1. Acct_1 logged to the system.
2. Acct_3 logged in to the system.
3. Acct_2 logged in to the system.
4. Assign permissions on Acct_1.
5. Delete record on table building with id 80
jsFiddle
Yes you can use ajax for this and simply update a div in your html.
You need to have jquery linked in order to use the below code.
show_log(){
var lnk = "link to the viewlog.php file";
$.ajax({url:lnk,success:function(result){
$("#log_div").html(result);
}});
}
Run the show_log() function every x number of mins.
Have your viewlog.php show the last x number of records in the descending order of time.
You can update your sql to look like
$sql = "select log_description,log_time from log ORDER by log_time DESC LIMIT 5 ";
You can use the below inside your javascript to run the function every x number of seconds. In this every 10 seconds.
window.setInterval(function(){
show_log();
}, 10000);
the 10,000 is in miliseconds
----- Try the below
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
http = getHTTPObject();
function getHTTPObject(){
var xmlhttp;
if(!xmlhttp && typeof XMLHttpRequest != 'undefined'){
try {
xmlhttp = new XMLHttpRequest();
}catch(e){
xmlhttp = false;
}
}
return xmlhttp;
}
function show_log(){
var url = "viewlog.php";
http.open("GET", url, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function handleHttpResponse(){
if(http.readyState == 4){
document.getElementById('log_div').innerHTML = http.responseText;
}
}
setInterval ( "show_log()", 5000 );
</script>
</head>
<body>
<div id="log_div"></div>
</body>
</html>
I am working on the PHP cart timer script using PHP and jQuery/JavaScript.
I am iterating the set-interval function every seconds to get the PHP's current time-stamp.
When the first product is added to the cart, the timer begins before getting timer-stops it prompts the user, whether the user want to continue or cancel.
My code is follows
$(document).ready(function(){
var orderedtime = "echo $_SESSION['ordertime'];";
if (orderedtime === null || orderedtime == ''){
console.log("orderedtime is not set");
}
else{
init();
}
});
var currenttime;
var alerttime;
var extratime;
function cd(){
alerttime = "<?php echo date('h:i:s', (strtotime($_SESSION['ordertime']) + (1 * 60))); ?>"
extratime = "<?php echo date('h:i:s', (strtotime($_SESSION['ordertime']) + (2 * 60))); ?>";
redo();
}
function redo(){
currenttime = "<?php echo date('h:i:s', time()); ?>";
if(alerttime == currenttime) {
//doing something
}
else if(currenttime == extratime){
//doing something
}
else{
cd = setTimeout("redo()",1000);
}
}
function init(){
cd();
}
The currenttime variable only storing the 1st iteration value is not getting updating.
How to solve this issue?
Please kindly help me to solve it.
Thanks in advance.
You're not actually requesting a time from the server in your setTimeout loop.
This line
currenttime = "<?php echo date('h:i:s', time()); ?>";
is set when the page is first generated and not changed again. If you want the time updated you need to send a request to the server. This probably isn't the best way to do it though.
Further to MikeW's excellent but incomplete answer, you need a way to request the time from the server and receive it back in the DOM.
There is only one way to do that: AJAX.
As Mike pointed out, the PHP code that you typed above only runs once: when the page is first generated. After the page has been generated and the document is "ready", you must use AJAX.
Below is a fully-working, copy/pastable example to demonstrate one way this could work.
Note that I had to over-ride the orderedtime variable because I don't know how/when you set that.
HTML/javascript side: index.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<style>
#timeDiv{width:40%;height:200px;background:wheat;padding:10px;}
</style>
<script type="text/javascript">
$(document).ready(function() {
//var orderedtime = "<?php echo $_SESSION['ordertime']; ?>";
var orderedtime = '';
if (orderedtime === null || orderedtime == ''){
console.log("orderedtime is not set");
}else{
doAjax();
}
window.setInterval(function(){
doAjax();
},2000);
}); //END document.ready
function doAjax() {
$.ajax({
type: "POST",
url: "get_the_time.php",
data: "ordertime=" + orderedtime,
success: function(myData) {
$('#thetime').html(myData);
}
});
}
</script>
</head>
<body>
<div id="timeDiv">
The time is: <span id="thetime"></span>
</div>
</body>
</html>
PHP side: get_the_time.php
<?php
if (isset($_POST['ordertime']) != true) {
$d = date("h:i:s");
}else{
$ot = $_POST['ordertime'];
$d = date('h:i:s', (strtotime($ot) + (1 * 60)));
}
echo $d;
IMPORTANT NOTE:
When using AJAX, the response sent from the server is received inside the success: function, and no where else.
If you later wish to use that data, assigning it into a variable inside the success function will not work. The best way I have found is to stick the received data into an element of some kind (a hidden input field works great for this), and then retrieve it from there when needed.
For example:
<input type="hidden" id="myHiddenField" />
$.ajax({
type: "POST",
url: "get_the_time.php",
data: "ordertime=" + orderedtime,
success: function(myData) {
$('#thetime').html(myData);
$('#myHiddenField').val(myData);
}
});
Then, inside some other javascript function, you can grab that data and assign it to some variable, thus:
var someVar = $('#myHiddenField').val();
Hope this helps, late as it is.
This stackoverflow post has further information/explanation regarding AJAX. Check out the simplified AJAX examples at the bottom.
I want to display the browsed time of a user, But when i refresh it, it will be again start from 0:0:0.
How can it handle?
<?php
$total_mints=($live_match['match_name']) * (60);
?>
<script language="javascript">
display_c(<?=$total_mints?>,'ct');
</script>
<script type="text/javascript">
function display_c(start,div){
window.start = parseFloat(start);
var end = 0 // change this to stop the counter at a higher value
var refresh=1000; // Refresh rate in milli seconds
if(window.start >= end ){
mytime=setTimeout("display_ct('"+div+"')",refresh)
}
else {alert("Time Over ");}
</script>
Once the time is over, you could set a cookie to 'Time Expired'... When the page is loaded, if the cookie is 'Time Expired' then you can display the 'Time Over' alert. You can also use the cookie to keep track of accumulated browsing time.
Edit - added some specifics... but I think you'll have to think about this some more.
Basically, you want to use JS to write the cookie as the user uses the page, and you want to use PHP to read the cookie when the page is loaded. You can use the cookie to either only track whether time is up, total accumulated time, or both. I think you'd want to renew the cookie every minute or so?
It's going to look SOMETHING like this - this code just shows how to keep track of whether time has expired or not with a cookie, not accumulated time.
<?php
$total_mints=($live_match['match_name']) * (60);
// check for cookie and only proceed if it is not expired
// can also use cookie to keep track of total accumulated number
// of minutes between session
if ($_COOKIE["yourMints"] != "expired")
{
?>
<script language="text/javascript">
display_c(<?php echo $total_mints; ?>,'ct');
</script>
<script type="text/javascript">
function display_c(start,div)
{
window.start = parseFloat(start);
var end = 0 // change this to stop the counter at a higher value
var refresh=1000; // Refresh rate in milli seconds
if(window.start >= end )
{
mytime=setTimeout("display_ct('"+div+"')",refresh)
} else
{
alert("Time Over ");
// set cookie to expired
document.cookie = "yourMints=expired";
}
}
</script>
<?php
} else // What follows is what happens if cookies IS expired
{
?>
<script type="text/javascript">
alert("Time Over ");
</script>
<?php
}
?>
Here is a good JS cookies tutorial:
http://www.quirksmode.org/js/cookies.html
Here is using $_COOKIE to read cookies with PHP
http://php.net/manual/en/reserved.variables.cookies.php
EDIT: Added in JQuery example after seeing PlagueEditor's example.
Nice script PlagueEditor. Thought I'd try the same thing w/ JQuery for fun.
JQuery has a simple little cookie plugin... only 40 lines of code or so.
Here's a page with a cookie stored timer and a timeout of 10 seconds with a possible reset:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Time Spent on Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="PATH-TO-YOUR-JQ-DIRECTORY/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="PATH-TO-YOUR-JQ-DIRECTORY/cookie.js"></script>
<script type="text/javascript">
<!--
$.myTimer =
{
timeLimit: 10,
displayTime: function ()
{
if ($.myTimer.time < $.myTimer.timeLimit)
{
$("#timeHere").html($.myTimer.time);
$.cookie('yourMints', $.myTimer.time, { expires: 7});
++$.myTimer.time;
$.myTimer.toggle = setTimeout("$.myTimer.displayTime()",1000);
} else
{
$("#page").html('<h1>Time expired</h1>');
}
}
}
// When the page is ready ==================================================
$(document).ready(function()
{
// Read time spent on page cookie. Set it, if it doesn't exist.
if (!$.cookie('yourMints'))
{
$.cookie('yourMints', '0', { expires: 7});
}
$.myTimer.time = $.cookie('yourMints');
// Start timeer
$.myTimer.displayTime();
// Reset the timer
$("#reset").click( function()
{
$.cookie('yourMints', '0');
window.location.reload();
});
});
// -->
</script>
</head>
<body>
<div id="page">
<h2>Your total time here: <span id="timeHere"></span></h2>
You can only look at this page for 10 seconds.
</div>
<input id="reset" type="button" value="Reset Timer" />
</body>
</html>
Below is a solution for keeping track of the browsed time, even with refreshing. It gets the date when the page loads and every second subtracts that date from the given date. The date is then displayed in the span. The page should work by itself. I hope this is what you were looking for, or at least helps. Two functions were W3Schools examples*.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<script type="text/javascript">
/**
* getCookie and setCookie were taken from http://www.w3schools.com/JS/js_cookies.asp.
*/
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}
var totalTime=0;
var storedTime=getCookie("storedTime");
if(storedTime.length == 0){
//If it doesn't exist..
storedTime=0;
}else{
storedTime=parseInt(storedTime);
totalTime=storedTime;
}
function updateTime(){
totalTime+=1000;
document.getElementById("duration").innerHTML= Math.ceil(totalTime / 1000);
}
onbeforeunload = function(){
setCookie("storedTime",totalTime,3);
}
setInterval(updateTime, 1000);
</script>
Your total time here: <span id="duration"><script type="text/javascript">document.write( Math.ceil(totalTime / 1000));</script></span> seconds...
</body>
</html>