简体   繁体   中英

Auto refresh included PHP file inside a DIV

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?

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>

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/

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
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM