michelle
michelle

Reputation: 653

refresh table only on changes

I'm using setTimeout + .load to reload my php file: table.php every 5 seconds, but I don't want it to reload the file if there isn't a change. A solution I came up with is to create a file called changes.php which currently echos 1 if there's a change or 0 if there isn't. If changes.php echos 1 I would like to refreshTable else it needs to wait another 5 seconds to check again. Any help would be appreciated as I'm confused with how to handle the javascript portion.

<div id="table"></div>

   <script type="text/javascript">
$(document).ready(function(){
  refreshTable();
});

function refreshTable(){
 // if changes.php = 0 then load table.php else wait another 5 seconds
    $('#table').load('table.php', function(){
       setTimeout(refreshTable, 5000);
    });
}
</script>

Upvotes: 1

Views: 218

Answers (1)

AndreFeijo
AndreFeijo

Reputation: 10639

<script>

$(document).ready(function(){
    checkForChanges();
    setTimeout(checkForChanges, 5000);
});

function checkForChanges() {
   $.get("changes.php", function(response) {
      if(response === "1") {
         refreshTable();
      }
   });
}

function refreshTable(){
    $('#table').load('table.php');
}

</script>

Upvotes: 1

Related Questions