Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

210
Visualizações
Repeat jQuery ajax call

How to repeat jQuery ajax call every 10 seconds?

$(document).ready(function() {
    $.ajax({    
        type: "GET",    
        url: "newstitle.php",   
        data: "user=success",    
        success: function(msg) {
            $(msg).appendTo("#edix");    
        }  
    });

I've tried to wrap the $.ajax with a function and to call the function with setInterval

$(document).ready(function() {
    function ajaxd() { 
        $.ajax({
            type: "GET",
            url: "newstitle.php",
            data: "user=success",
            success: function(msg) {
                $(msg).appendTo("#edix");
            }
        });
    }
    setInterval("ajaxd()",10000);
});

But it says "ajaxd is not defined"

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Your method should not be placed inside the ready method, or it would only be available there and not outside.

$(document).ready(function() {
    setInterval(ajaxd, 10000);
});

function ajaxd() { 
  $.ajax({
   type: "GET",
   url: "newstitles.php",
   data: "user=success",
   success: function(msg){
     $(msg).appendTo("#edix");
   }
 });
}
over 4 years ago · Santiago Trujillo Relatório

0

Better approach would be to use setTimeout, so you only make a request when the previous one is done.

How it should be done

Imagine that request for some reason (server malfunction, network error) takes longer than defined time. You'll have many simultaneus requests, which isn't any good. And what if you decide to shorten the time difference from 10 seonds to 1 second in the future?

$(function() {
  var storiesInterval = 10 * 1000;
  var fetchNews = function() {
    console.log('Sending AJAX request...');
    $.ajax({
      type: "GET",
      url: "newstitles.php",
      data: {
        user: 'success',
        some: ['other', 'data']
      }
    }).done(function(msg) {
      $(msg).appendTo("#edix");
      console.log('success');
    }).fail(function() {
      console.log('error');
    }).always(function() {
      // Schedule the next request after this one completes,
      // even after error
      console.log('Waiting ' + (storiesInterval / 1000) + ' seconds');
      setTimeout(fetchNews, storiesInterval);
    });
  }
  
  // Fetch news immediately, then every 10 seconds AFTER previous request finishes
  fetchNews();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I know, after 6 years. But still, I thought it's worth for other people.

Why the OP's code didn't work?

It's worth noting that your code didn't work mainly, because you passed your ajaxd() function call as a string to setInterval. It's not a good practice, partly because setInterval will expect the functions to be defined globally. You should use reference to a function, like in my example. That way, it doesn't matter where your function is defined and if it's anonymous or not.

over 4 years ago · Santiago Trujillo Relatório

0

$(document).ready(function() {

setInterval(function() { 
  $.ajax({
   type: "GET",
   url: "newstitle.php",
   data: "user=success",
   success: function(msg){
     $(msg).appendTo("#edix");
   }
 });
}, 10000);

});
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda