Refresh div every x seconds

0

I have a div and within it I call a method of a class in PHP that shows some information from the database.

Something like that

<div id="Ejemplo">
  <?php $ejemplo = new ClaseYoQueSe(); echo $ejemplo->Mostrar_dato(); ?>
</div>

The idea is that this div can be updated every X time without the need for the user to do a full page rewind.

Thanks in advance!

And out of curiosity, is there any way to update only when the value changes, in order to avoid unnecessary updating? I guess not, because somehow you have to know if the data has changed, and you should also evaluate it every X time.

    
asked by Omar 07.05.2018 в 22:40
source

1 answer

1

You can use $.ajax() from jQuery to make a request every certain amount of time with setInterval() , per example:

javascript:

$(document).ready(function() {
  // intervalo
  setInterval(function() {
    // petición ajax
    $.ajax({
      url: 'claseYoQueSe.php',
      success: function(data) {
        // reemplazo el texto que va dentro de #Ejemplo
        $('#Ejemplo').text(data);
      }
    });
  }, 10000); // cada 10 segundos, el valor es en milisegundos
});

PHP (file claseYoQueSe.php )

<?php
  $ejemplo = new ClaseYoQueSe(); echo $ejemplo->Mostrar_dato();
  // formateo a json para javascript
  json_encode($ejemplo);
?>
    
answered by 07.05.2018 в 22:49