Andante88
Andante88

Reputation: 65

Auto-refresh <div> text

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.

Upvotes: 2

Views: 22129

Answers (3)

user6079755
user6079755

Reputation:

try Via Ajax

function doRefresh(){
   $.ajax({
      url : "helloworld.txt",
      dataType: "text",
      success : function (data) {
         $(".text").html(data);
      }
   });
   setTimeout(function() {
      doRefresh();
   }, 2000);
}

$(document).ready(function () {
  doRefresh(); 
});

Check console for Error.

https://stackoverflow.com/a/6470614/6079755

Upvotes: 0

PeterKA
PeterKA

Reputation: 24648

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>

Upvotes: 3

Ɛɔıs3
Ɛɔıs3

Reputation: 7851

setInterval() method will continue be calling until clearInterval() method is called, or when window is closed. setTimeout() method calls a function after a specified number of milliseconds.

I'm used to treat such cases as the example below :

function doRefresh()
{
  $("#show").load("LOG.txt");
  setTimeout(function() {
    doRefresh();
  }, 2000);
}

$(document).ready(function () {
  doRefresh(); 
});

By calling function itself like this example, with the setTimeout() method, it will be called every 2 seconds.

See my jsfiddle version

Upvotes: 0

Related Questions