How do i auto refresh my div class content? - javascript

My code is as follows -
<div class="huge">
<?php echo date ("g:i:s A"); ?>
</div>
How do i set <div class="huge"> to refresh every second?

Assuming that you need to get the update from the server (noted the PHP code in your original post), there are two things you need to implement:
A Server-Side script (in this case written in PHP) to be requested by the client for fresh data.
A Client-Side javascript to fetch fresh data from the server and update your div.
Let's make an example.
index.php
<html>
<head>
<title>My date updater</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>
<body>
<div class="huge"><?php echo date ("g:i:s A"); ?></div>
</body>
</html>
Javascript (using jQuery)
setInterval(function(){
$.ajax({
url:'loadData.php'
}).done(
function(data){
$('.huge').html(data);
});
},1000);
loadData.php
<?php echo date ("g:i:s A"); ?>
Initially your page named in this example index.php will load and show the initial date (using a bit of php code inline).
Then the javascript will start to get data from the server (using an ajax request to loadData.php) every second and the div will be updated with the fresh data.
Hope it helps a bit!
P.S: Date and time information can also be fetched using pure javascript code on the client-side, but for some applications the date and time information on the client-side is not reliable enough since it relies on the date and time settings that are set by the client browser.

You could use Ajax, something like this:
If it's just simple text, or simple HTML being loaded then you could use
setInterval(function(){
$("#huge").load("now_playing.php");
...
}, 5000);
You could also use something like:
function reload() {
jQuery.ajax({
url: "fetch_message.php",
type: "POST",
success:function(data){
$('#huge').innerHTML(data);
setTimeout(function(){
reload()
}, 1000);
}
});

This will update the content of the element with id="huge" every second. you don't need any initial php value.
If you need other elements like minutes and seconds of course you can add dt.getMinutes() and dt.getHours() to the string.
<div id="huge"></div>
<script language="javascript">
function refreshSomething(){
var dt = new Date();
document.getElementById('huge').innerHTML = dt.getSeconds();
}
setInterval(function(){
refreshSomething() // this will run after every second
}, 1000);
</script>

This works too -
<script>function getTime(){
var date = new Date();
date.setTime(Date.now());
return (date.getHours() % 12) + ':' + leadingzero(date.getMinutes()) + ':' + leadingzero(date.getSeconds()) + (date.getHours() < 12 ? ' AM' : ' PM'); ;
}
function leadingzero(n) {
return (n < 10) ? ("0" + n) : n;
}
function updateDiv(){
var d = document.document.getElementsByClassName('yourDivClassname')[0];
d.innerHTML = getTime();
}
setInterval(updateDiv, 1000);</script>

Related

How to put the server's current timestamp into strtotime() function automatically PHP?

I am trying to make a program which counts down over the space of 15 seconds and displays them using PHP and JQuery. I need to be able to automatically load the server's timestamp into the strtotime function and set this to the start point of the timer, and make the end point of the timer 15 seconds after this point, is there any way I can achieve this?
I have tried setting the times specifically and the timer works for counting to 15 seconds after these points, but I need it to set these times relative to the current moment automatically, as I want it to start and stop the timer at certain undecided points in the program as it is running. I have also tried the reference values 'now' and '-15 seconds' - but these seem to stop the timer at '15 seconds remaining' and it does not count down from this point.
timer.php:
<?php
if(true) {
$countdownEnd = strtotime("-15 seconds");
$countdownStart = strtotime("now");
$timeLeft = $countdownEnd - $countdownStart;
if(isset($_POST["type"]) === true && $_POST["type"] == "timerupdate") {
echo ($timeLeft);
}
}
?>
timer.js:
$(function() {
var timerText = $("[timer]");
setInterval(function() {
$.post("timer.php", {type : "timerupdate"}, function(data){
timerText.html(data + " seconds remaining")
});
}, 1000);
});
timer tests.php:
<!DOCTYPE HTML>
<html>
<head>
<script type="application/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="application/javascript" src="timer.js"></script>
</head>
<body>
<?php include("timer.php") ?>
<p timer></p>
</body>
</html>
I expect the output to be a timer which counts down from 15 seconds whenever the starting condition (the if statement at the beginning of timer.php) becomes true.
Any help is really appreciated, thanks :)
If you want to save the timer after reload you need something like a session with a cookie. have a look at https://php.net/manual/en/function.session-start.php
//start a session and make sure there is no output before
session_start();
//maybe you want to check for the requestmethod before you do additional checks
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//your check for timerupdate.
//you dont have to exact bool compare to true the isset it can only return true or false.
if (isset($_POST["type"]) && $_POST["type"] == "timerupdate") {
if (!isset($_SESSION['time'])) $timeLeft = 15;
else $timeLeft = 15 - (time() - $_SESSION['time']);
//output the timer or whatever you want
if ($timeLeft < 0) echo 0;
else echo $timeLeft;
}
}
you have to add settings: withCredentials: true into your ajax call in order to send cookies
Can you check with using date function with time .

window location href not reloading

I am working with javascript and php, and I want to send variables from an html file to a php file continuously, but the method window.location.href only send it one time, despite I call the function every second. How do I keep sending data continuously using window.location.href?
HTML file:
<head>
<script type="text/javascript" src="zepto.min.js"></script>
<script type="text/javascript">
function refresh() {
var wind = 255;
var rain = 1;
var speed = 56;
window.location.href = "http://localhost/getData.php?s1=" + wind +"&s2=" + rain + "&s3=" + speed;
}
</script>
</head>
<body onload="setInterval(refresh, 1000);">
</body>
when you use window.location.href = 'http://somewhere, the browser looses context and your variables are lost.
a smarter way to keep sending variables to your server is by using the ajax function of zepto or jquery
$.get("http://localhost/getData.php?s1=" + wind +"&s2=" + rain + "&s3=" + speed", function(){
console.log('server received information');
})

Getting website's time to set time range

Is there any way to get the current time of website in order to set range time for reaction?
e.g if current time of website >= 14:00 && current time of website < 15:00
do reaction
else
another reaction
I want to do this checking type of fuction every 30' sec
EDITED
e.g If in my country the time is 14:00 and in another one is 19:00 I want to do the reaction to another country based in my country's time. Correct my if I do smthng wrong.
here is the code for php file to fetch server time, name it t.php.
<?php
$b = time ();
echo date("H",$b);
?>
and here is the code for other file on which you use ajax: Run this file using xamp/wamp.
Place both files in sane directory .
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
setInterval(function() {
$.ajax({
url : "t.php",
type: 'GET',
success: function(data){
if(data >= 9 && data < 10){
alert('yes');
// do something
} else{
alert('no');
// do something
}
}
});
}, 1000);
</script>
Here is the Solution:
you can find current time of website using javascript because it is a client side scripting language
In php I think there is no way to find client's time (not sure), That's why I am using jquery.
to use it in php file use ajax.
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function(){
function call_notification_count() {
var todaydate = new Date(); // current time of browser. or you can say Time of client's location
var month = todaydate.getMonth()+1+"";if(month.length==1) month="0" +month;
var date = todaydate.getDate()+"";if(date.length==1) date="0" +date;
var year = todaydate.getFullYear();
var hours = todaydate.getHours();
var minutes = todaydate.getMinutes();
var seconds = todaydate.getSeconds();
var todaytime = hours+":"+minutes+":"+seconds;
var todaydateonly = year+"-"+month+"-"+date+" ";
alert(todaytime);
if(hours >= 14){
// do something
}else{
// do something
}
}
setInterval(call_notification_count, 3000); // Set time intervel here like for every 30 sec.
});
</script>

Automatically update with AJAX

I'm currently using this code on my webpage:
<?php
$url = "https://www.toontownrewritten.com/api/invasions";
$data = json_decode(file_get_contents($url));
if (!empty($data->invasions)) {
echo "<h1 style='text-align:center;margin:auto;padding:2px;font-size:16px;font-weight:bold;text-decoration:underline;padding:2px;'>Invasion Tracker</h1>";
$i = 0;
foreach($data->invasions as $title => $inv) {
print "<h3 style='text-align:center;margin:auto;'><b>District:</b> {$title}
</h3><br style='font-size:1px;'><h3 style='text-align:center;margin:auto;'><b>Cog:</b> {$inv->type}
</h3><br style='font-size:1px;'><h3 style='text-align:center;margin:auto;'><b>Progress:</b> {$inv->progress}
</h3>";
if (count(($data->invasions) > 1)) {
if (end($data->invasions) !== $inv) {
print "<hr>";
} else {
print "<br style='font-size:2px;'>";
}
}
}
} else {
echo "<h1 style='text-align:center;margin:auto;padding:2px;color:darkred;font-weight:bold;'>No invasions!</span>";
}
?>
I'm looking to make it refresh every 10 seconds via AJAX. However, I keep reading you need to make a function, but I'm not sure how I'd do that with the API? Every 10 seconds, that API is being updated, which is why I'd like this to be updated with AJAX every 10 seconds. Currently, I have it so the user has to manually refresh. Any help is appreciated!
You can simply reload the page with the method proposed here
But if you wanna have an AJAX implementation which just refereshes a part of your html nice and tidy, You gonna have to
Almost forget your PHP code
use the following code to implement the request to the url
$.ajax({
url: "https://www.toontownrewritten.com/api/invasions",
})
.done(function( data ) {
if ( console && console.log ) {
console.log( data );
}
});
Make a JS code which would convert the data got in the previous section to a readable html and show it on your page. It should be implemented in the the block where console.log(data) is.
Put that part of code in a setInterval
setInterval(function(){
//$.ajax();
}, 10000);
And be aware that you are gonna go to hell if your request doen't complete in the interval. see this .
I have a better suggestion, again it is same as using setInterval.
setInterval(function () {
if (isActive) return; // so that if any active ajax call is happening, don't go for one more ajax call
isActive = true;
try {
$.ajax("URL", params,function() { isActive = false;//successcallback }, function () {
isActive = false; // error callback
});
} catch (ex) { isActive = false;}
}, 10000);
Your problem is a failure to understand AJAX. Below is a $.post() example.
First let's make the page that you want your Client (the Browser user) to see:
viewed.php
<?php
$out = '';
// you could even do your initial query here, but don't have to
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<style type='text/css'>
#import 'whatever.css';
</style>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='whatever.js'></script>
</head>
<body>
<div id='output'><?php /* if initial query took place */ echo $out; ?></div>
</body>
</html>
Now you need your JavaScript in whatever.js.
$(function(){
function getData(){
$.post('whatever.php', function(data){
// var htm = do a bunch of stuff with the data Object, creating HTML
$('#output').html(htm);
});
}
getData(); // don't need if PHP query takes place on original page load
setInterval(getData, 10000); // query every 10 seconds
});
On whatever.php:
<?php
// $assocArray = run database queries so you can create an Associative Array that can be converted to JSON
echo json_encode($assocArray);
?>
The JSON generated by PHP shows up in the data argument, back in the JavaScript that created your PHP request:
$.post('whatever.php', function(data){

Javascript - checking if cookie exists on page load isn't working for me

I have the follwing code :
<script type="text/javascript">
function myfuncc () {
if (document.cookie.indexOf("visited") >= 0) {
// They've been here before.
alert("hello again");
}
else {
// set a new cookie
expiry = new Date();
expiry.setTime(date.getTime()+(10*60*1000)); // Ten minutes
// Date()'s toGMTSting() method will format the date correctly for a cookie
document.cookie = "visited=yes; expires=" + expiry.toGMTString();
alert("this is your first time");
}
}
</script>
<script type="text/javascript">
window.onload = myfuncc;
</script>
As you can see the window.onload function, I am trying to check if a vistor had already been at the site once the page loads. I am using cookies to do so. Problem is, I can't see the messages I am supposed to. Anyone knows why?
You have to set the expire date using toUTCString() method.
You also have a date object that is not initialized, try this:
function myfuncc () {
if (document.cookie.indexOf("visited") >= 0) {
// They've been here before.
alert("hello again");
}
else {
var expiry = new Date();
expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes
document.cookie = "visited=yes; expires=" + expiry.toUTCString();
alert("this is your first time");
}
}
give this a try:
var testarr = ["knirpsel", "text", "visited=yes"].indexOf("visited");
alert ( testarr );
output is "-1" which means the string "visited=yes" won't be found by search term "visited"
http://jsfiddle.net/m5x3M/
and
What is the best way to get a cookie by name in JavaScript?

Categories

Resources