AutoUpdate included php file inside div

I have a file called messages.php that launches SQL queries to the database and displays the results in a variable $res

My menu.php page I used

include 'messages.php';

And then:

<div id="msgs">
<?php echo $res; ?>
</div>

Thus, it displays all the data in a variable $reson the messages.php page in the div on menu.php

How can I do this to automatically update so that all new data in the variable is $resdisplayed without updating the menu.php page?

+3
source share
3 answers

Delete first include 'messages.php'; Then remove echo $ res; from the div and put it in the last line of messages.php

and try the following code after including 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>
+2
source

jQuery. JS, JS , jQuery.

function reload_messages(){
    $.get("messages.php", function(data) {
        $("#id").html(data);
    });
}

reload_messages, :

<a href="javascript:reload_messages();">reload messages</a>

.get, : https://api.jquery.com/jQuery.get/

+1

If you want it to be updated at intervals, you can use setInterval

setInterval( refreshMessages, 1000 );

1000 - 1000 milliseconds, so for 1 second change this as you like.

So, every 1 second it calls the refreshMessages function:

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
    });
}
+1
source

All Articles