Update div every X seconds

1

I need a function to recharge one every X seconds because the value of the BBDD can change. I have the following, but I do not update the value. What fails me?

div:

<div id="results">valor a cargar</div>

The script:

function sendRequest(){
    $.ajax({
        url: "ajax/count.php",
        success: 
          function(result){
           $('#results').text(result);
           setTimeout(function(){
          sendRequest();
           }, 3000);
        }});
});

and the code in "ajax / count.php" returns the total values of a table:

while($row = mysql_fetch_assoc($result))
{
    echo $row['TOTAL'];        
}
    
asked by Guif If 30.03.2018 в 21:30
source

2 answers

2

There are a couple of issues to consider:

1) if you use interval in an asynchronous call, it may be the case that you ask for something again before the previous answer arrives

2) the version of jquery that you use should be the min and not the slim

<script src="https://code.jquery.com/jquery-3.3.1.min.js">

instead of

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js">

functional code, note that I use the oncomplete to launch the new request

<!DOCTYPE html>
<html lang="es">
<head>
<title>ajaxreload</title>
<style>
</style>
</head>
<body>
<div id="results"></div>
</body>
<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
<script>
function sendRequest(){
  $.ajax({
    url: "ajax/count.php",
    success:
      function(result){ 
/* si es success mostramos resultados */
       $('#results').text(result);
    },
    complete: function() { 
/* solo una vez que la petición se completa (success o no success) 
   pedimos una nueva petición en 3 segundos */
       setTimeout(function(){
         sendRequest();
       }, 3000);
      }
    });
  };

/* primera petición que echa a andar la maquinaria */
$(function() {
    sendRequest();
});

</script>
</html>
    
answered by 30.03.2018 / 22:06
source
1

Use setInterval instead of setTimeout since setTimeout will wait three seconds and then run.

setInterval will be running every three seconds in your case.

I hope you serve

function sendRequest() {
  $.ajax({
    url: "ajax/count.php",
    success: function(result) {
      $('#results').text(result);
    }
  });
});

setInterval(function(){ 
   sendRequest();
}, 3000);
<div id="results">valor a cargar</div>
    
answered by 30.03.2018 в 22:00