Auto-refresh <div> text

16,417

Your code is mostly correct. However, you want to make sure that you only fire the function only at DOM ready, if your code is in the header. And of course you have to include jQuery.

NOTE: If you place your code just before </body> as it is, it should work.

<script src="http://code.jquery.com/jquery-3.1.1.js"></script>
<script type="text/javascript">
    function doRefresh(){
        $("#show").load("LOG.txt");
    }
    $(function() {
        setInterval(doRefresh, 5000);
    });
</script>
Share:
16,417
Andante88
Author by

Andante88

Updated on June 16, 2022

Comments

  • Andante88
    Andante88 almost 2 years

    This has been well answered several times, but being new to js I must be missing something basic.

    My simple chat page works well, but refreshes only on manual call, and I want it to auto-refresh.

    The php fetches the comment via POST, writes it to the log file (in the same directory), then writes the updated log file to the div.

    <div id="show"><?php include 'LOG.txt' ; ?></div>
    

    I adapted the following code from another post and tried it in header and in body, but it is not working.

    <script type="text/javascript">
        function doRefresh(){
            $("#show").load("LOG.txt");
        }
        setInterval(function(){doRefresh()}, 5000);
    </script>
    

    What does this need?

    Thank you.

  • Andante88
    Andante88 over 7 years
    Very helpful. Thank you.
  • Andante88
    Andante88 over 7 years
    Very helpful. Thank you.
  • PeterKA
    PeterKA over 7 years
    Glad you found this helpful. Please feel free to upvote and accept as answer if your issue was resolved by this code.
  • Andante88
    Andante88 over 7 years
    Load frequency: Could there be a problem with 1 sec? Low lag is nice for chat. This is an ultra light siuation: private website, unlimited-bandwidth hosting, 5k page file, log file truncates to 5k, one pair of users. Testing with dual browsers seems fine. But am I missing something? Thank you.
  • Shrenik
    Shrenik over 3 years
    @PeterKA This no longer works due to an error that every browser reports - Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///... developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/… . Do you have an alternative solution that may still work?
  • PeterKA
    PeterKA over 3 years