Reputation:
I have a file called messages.php which runs SQL queries to a database and displays results in a $res
variable
My menu.php page I used
include 'messages.php';
And then:
<div id="msgs">
<?php echo $res; ?>
</div>
So this displays all the data in the $res
variable from the messages.php page in a div on menu.php
How can i make this automatically refresh so any new data in the $res
variable displays without having to refresh the menu.php page?
Upvotes: 3
Views: 13667
Reputation: 4173
If you want it to refresh on an interval, you can make use of setInterval
setInterval( refreshMessages, 1000 );
1000
is 1000 milliseconds, so 1 second, change this to how you like.
So every 1 second it triggers the function refreshMessages:
function refreshMessages()
{
$.ajax({
url: 'messages.php',
type: 'GET',
dataType: 'html'
})
.done(function( data ) {
$('#msgs').html( data ); // data came back ok, so display it
})
.fail(function() {
$('#msgs').prepend('Error retrieving new messages..'); // there was an error, so display an error
});
}
Upvotes: 1
Reputation: 608
First Remove include 'messages.php'; Then remove echo $res; from div and put it in the last line of messages.php
and try the following code after including the jquery file
<script>
jQuery().ready(function(){
setInterval("getResult()",1000);
});
function getResult(){
jQuery.post("messages.php",function( data ) {
jQuery("#msgs").html(data);
});
}
</script>
<div id="msgs">
</div>
Upvotes: 2
Reputation: 5758
This requires the jQuery library. It could be done in pure JS, but if you're a JS beginner I recommend using jQuery.
function reload_messages(){
$.get("messages.php", function(data) {
$("#id").html(data);
});
}
You will then need to call reload_messages, for example:
<a href="javascript:reload_messages();">reload messages</a>
If you want to expand on the .get method, check out this page: https://api.jquery.com/jQuery.get/
Upvotes: 1