Auto-refresh PHP display variable - php

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.

Related

jquery addclass keeps reseting inside setinterval

I have an HTML DIV which is updated by ajax function using setinterval. What I'm trying to do is addclass to the result of ajax. But when setinterval the addedclass is reset and displays the initial class. how to solve this issue.
<html>
<body>
<div id="something"></div>
<script>
$(document).ready(function(){
var id;
setInterval(function(){
somepage();
addactiveclass();
}, 5000);
function somepage(){
$.ajax({
url:"fetchcontents.php",
method:"POST",
success:function(data){
$('#something').html(data);
}
})
}
function addactiveclass(){
$('#list-'+id).addClass("active");
}
// UPDATED
$(document).on('click', '.mycontents', function(){
id = $(this).data('id');
$('#list-'+id).addClass("active");
}
});
</script>
</body>
</html>
UPDATE: fetchcontents.php
<?php
$output .= '<div class="list-item mycontents" data-id="'.$row['id'].'" data-name="'.$row['username'].'" id="list-'.$row['id'].'">';
//.... some php function to generate some contents inside the above div.....
// Contents do not interfere with this question.
$output .= '</div>';
echo $output;
?>
What happens is the active clas is not added to the div id="list-'.$row['id'].'". As you know setinterval keeps on executing ajax function after 5sec and the active class is reset and not displayed.
Could anyone please guide me to accomplish this issue.
Thanks in advance.
I just ran your code in jsfiddle, but replaced the ajax with a string defining a new div as contents of #something, and it works.
However it did require me to put the js inside a $(document).ready block
$(document).ready(function() {
//your js in here
})
Try that. What this does is not define the js until all the HTML is rendered. My guess is that you were referencing #something before it existed.
EDIT:=============================================
You have changed your code considerably since my answer was written, but to backup my claim to have a solution to what I believe was your question, I have re-done my jsfiddle test: https://jsfiddle.net/uf5h0sgw/
<html>
<body>
<div id="something">AAAA</div>
<script>
$(document).ready(function(){
var id;
var cnum = 1;
setInterval(function(){
somepage();
addactiveclass();
}, 1000);
function somepage(){
$('#something').html('<div class="abc">BBBB</div>');
/*$.ajax({
url:"fetchcontents.php",
method:"POST",
success:function(data){
$('#something').html(data);
}
})*/
}
function addactiveclass(){
/*$('#list-'+id).addClass("active"); */
$('#something div').addClass("active" + cnum++)
}
});
</script>
</body>
</html>
I cannot reproduce your ajax response, so I have just added some code to insert a DIV into #something every time the interval expires (reduced to 1000ms for the test).
Then the function addactiveclass() changes the class of the Div that has been added. I change the class name on a counter each loop so you can see that the class is updated every time around.
You will obviously have to adapt my code to handle what ever content your AKAX adds, but the approach should achieve what I think you want.

"Automatically update time in PHP using Ajax - display

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");
?>

Refresh a div with php data every 10 seconds using jQuery

Am trying to refresh data stored in a div every 10 seconds using jQuery.
My HTML code is:
<!DOCTYPE html>
<head>
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
setInterval(function() {
$("#latestData").load("getLatestData.php #latestData");
}, 10000);
});
</script>
</head>
<body>
<div id = "latestData">
</div>
</body>
</html>
And the PHP code I am using (temporarily as I know this won't change due to the same "data"):
<?php
echo "test";
?>
However, it isn't even showing "test" on the html page.. could anyone suggest where I have gone wrong?
Many thanks
jQuery load method works in a different way. Try reading its documentation.
You don't have to specify destination element ID twice, remove the second one, like this:
$("#latestData").load("getLatestData.php");
Here's a way that will solve what you want to achieve, using the $.get method in jQuery:
$(document).ready(function () {
setInterval(function() {
$.get("getLatestData.php", function (result) {
$('#latestData').html(result);
});
}, 10000);
});
If you want to refresh message count just use this code:
$(document).ready(function () {
setInterval(function () {
$("#ID").load();
}, 1000);
});

pass query string variables without refresh page

My question is that how to pass query string variables on same page without refreshing the page in php? My code is given below:
<img src="a.jpg">
<?php
$a = $_GET['id'];
$b = $_GET['pid'];
?>
Please help me to resolve this issue
<html>
<head>
<title>Test</title>
<meta name="" content="">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#image_id").click(function(){
var dataString = 'a=10&b=20';
$.ajax({
type:'POST',
url:'foo.php',
data:dataString,
success:function(data) {
if(data=="Something") {
// Do Something
} else {
// Do Something
}
}
});
});
});
</script>
</head>
<body>
<img id="image_id" src="images/bg.jpg" />
</body>
</html>
Then in the 'foo.php' page do this
if(isset($_POST['a'])) {
// DO SOMETHING
}
Remember the things that you want to send to the 'data' of
success:function(data)
must be echoed out in the foo.php page
You can't.
PHP requires execution on the server and so you'd have to either use AJAX and update your page accordingly, or just refresh your page.
You can by sending an AJAX request to the server. Ajax is a way to send asynchronous request via Javascript. Notice that jQuery has a good library about it.
Use jquery to resolve this. By using the $.ajax in jquery you can do the stuff you need without page refresh.

Ajax Auto Refresh php file in html

I'm a bit new to Ajax.
I've got a Ajax file which includes a php file and refreshes it every X seconds. That code for AJAX.PHP is:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script language="JavaScript">
setInterval( "SANAjax();", 10000 ); ///////// 10 seconds
$(function() {
SANAjax = function(){
$('#dataDisplay').fadeOut("slow").load('rand.php').fadeIn("slow");
}
});
</script>
<div id="dataDisplay"></div>
This code is working fine.
Bbut the html of AJAX.PHP page shows as it is code, while I want the output html of rand.php not javascript code given above. How can i do it?
suppost "rand.php" html out put (source) is: < html >< body >this is body <\ body ><\ html >.
I want this html to be shown on the html source of AJAX.PHP.
How can i do it?
If I mess any thing let me know, I'll try to make it more clear.
You need to run it. Not insert only as file.
$.post("rand.php", { },
function(data) { $('#dataDisplay').html(data) });
updated:
SANAjax = function(){
$.post("rand.php", { },
function(data) { $('#dataDisplay').fadeOut("slow").html(data).fadeIn("slow"); });
}
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_rand').load('rand.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
<div id="load_rand"> </div>
Don't forget to add the jquery library

Categories