Problem to run setInterval

Asked

Viewed 56 times

0

Good afternoon

I’m testing automate the search for record to the database with the script below:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="public/css/teste.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <!-- <script src="public/js/exibi.js"></script>  -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
  <script type="text/javascript">
    $(function() {
            var refreshAutomatico = setInterval(function(){
                $('tabela').load(Teste());
              }, 5000);
        });  
  </script>
</head>
<body>
    <div class="container">
      <div class="row">
          <div class="col-sm-6">
              <div id="resposta">
                <table border="1" width="500">
                      <thead>
                          <tr>
                              <th>ID</th>
                              <th>Nome</th>
                              <th>Acesso</th>
                          </tr>
                      </thead>
                      <tbody id="tabela">
                      </tbody>
                </table>
              </div>
          </div>
      </div>
    </div>
<script type="text/javascript">
          $(document).ready(
            function Teste(){
            $.ajax({
            type:'post',		//Definimos o método HTTP usado
            dataType: 'json',	//Definimos o tipo de retorno
            url: 'consulta.php',//Definindo o arquivo onde serão buscados os dados
            success: function montaTabela(dados){
            console.log(dados);
            for(var i=0;dados.length>i;i++){
              //Adicionando registros retornados na tabela
              $('#tabela').append('<tr><td>'+dados[i].id+'</td><td>'+dados[i].nome+'</td><td>'+dados[i].acesso+'</td></tr>');
            }

            
            }
          });
          });

</script>  
</body>
</html>

However, the error below is occurring:

Uncaught Referenceerror: Test is not defined at test.php:15

  • The first tag <script> is executed and the method Teste() has not yet been instantiated, so gives this error. Passes the method inside the second tag <script>.

  • Place your scripts after the tag </body>, and take advantage to adjust the loading order of your scripts.

  • @Edilson tried the two solutions but still keeps giving the same error: both if I put the Function of the setInterval block after or before the ajax block

2 answers

0

There are many problems in your code. First you could not access the function Teste() outside the $(document).ready because the function would have no scope in the other script block.

Another mistake is that you are putting the name Teste in the anonymous function of $(document).ready, when it should be a function within the function of .ready:

$(document).ready(function(){ // <-- função anônima do .ready
   function Teste(){}
});

Another more serious mistake is that you are using two AJAX at once: .load and $.ajax.

The method .load() is a simplified jQuery AJAX. Therefore, when you call the .load() to call another function with another AJAX, is totally meaningless.

If you want to load data into the element #tabela, or you use .load() or $.ajax. In your case, as it comes to JSON, just use the $.ajax because it is more complete and has options, unlike the .load().

Also not recommended to use setInterval to make requests from time to time. The ideal is to make one request after the other only when one has been completed (deal with it in the reply on this link).

Another thing is that $(document).ready(function(){}); is the same as $(function(){});, so it makes no sense to use two at the same time.

Your correct code would look like this:

$(document).ready(function(){

   function Teste(){
      $.ajax({
         type:'post',       //Definimos o método HTTP usado
         dataType: 'json',  //Definimos o tipo de retorno
         url: 'consulta.php',//Definindo o arquivo onde serão buscados os dados
         success: function(dados){
            console.log(dados);
            for(var i=0;dados.length>i;i++){
               //Adicionando registros retornados na tabela
               $('#tabela').append('<tr><td>'+dados[i].id+'</td><td>'+dados[i].nome+'</td><td>'+dados[i].acesso+'</td></tr>');
            }
         }
      });
   }

   var refreshAutomatico = setInterval(Teste, 5000);
});
  • Good morning @Sam thanks for the explanation, but while running with your code even increasing the time this pulling the first time the information and then it duplicates

  • Good morning. I think you have to empty it first: $('#tabela').empty().append(....

  • I think you should wear .html() instead of .append(). So you don’t even need to empty the table before: $('#tabela').html(...

0

I found that this way it pulls the information and does not duplicate, but I do not know if it would be the most correct way to execute such code so I am available for better suggestions

$(function() {
	var refreshAutomatico = setInterval(function(){
		$('#tabela').empty(); //Limpando a tabela
			$.ajax({
		  type:'post',		//Definimos o método HTTP usado
		  dataType: 'json',	//Definimos o tipo de retorno
		  url: 'consulta.php',//Definindo o arquivo onde serão buscados os dados
		  success: function montaTabela(dados){
			console.log(dados);
			for(var i=0;dados.length>i;i++){
			  //Adicionando registros retornados na tabela
			  $('#tabela').append('<tr><td>'+dados[i].id+'</td><td>'+dados[i].nome+'</td><td>'+dados[i].acesso+'</td></tr>');
			}
		  }
		});
		
	}, 50000);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.