How Do I Auto Refresh My Div Class Content?
Solution 1:
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><scripttype="text/javascript"src="https://code.jquery.com/jquery-2.2.4.min.js"></script></head><body><divclass="huge"><?phpecho 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
<?phpecho 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.
Solution 2:
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:
functionreload() {
jQuery.ajax({
url: "fetch_message.php",
type: "POST",
success:function(data){
$('#huge').innerHTML(data);
setTimeout(function(){
reload()
}, 1000);
}
});
Solution 3:
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.
<divid="huge"></div><scriptlanguage="javascript">functionrefreshSomething(){
var dt = newDate();
document.getElementById('huge').innerHTML = dt.getSeconds();
}
setInterval(function(){
refreshSomething() // this will run after every second
}, 1000);
</script>
Solution 4:
This works too -
<script>functiongetTime(){
var date = newDate();
date.setTime(Date.now());
return (date.getHours() % 12) + ':' + leadingzero(date.getMinutes()) + ':' + leadingzero(date.getSeconds()) + (date.getHours() < 12 ? ' AM' : ' PM'); ;
}
functionleadingzero(n) {
return (n < 10) ? ("0" + n) : n;
}
functionupdateDiv(){
var d = document.document.getElementsByClassName('yourDivClassname')[0];
d.innerHTML = getTime();
}
setInterval(updateDiv, 1000);</script>
Post a Comment for "How Do I Auto Refresh My Div Class Content?"