最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Auto refresh included PHP file inside a DIV - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Feb 6, 2014 at 10:27 Hasib Tarafder 5,8133 gold badges33 silver badges44 bronze badges asked Feb 6, 2014 at 10:26 user3223205user3223205 1
  • you can do it by useing jquery ajax – Vikas Gautam Commented Feb 6, 2014 at 10:30
Add a ment  | 

3 Answers 3

Reset to default 2

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 remend 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./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
    });
}
发布评论

评论列表(0)

  1. 暂无评论