Simple ajax to reload a DIV every 30 seconds

Asked

Viewed 722 times

0

I am the following javascript to reload a div every 30 seconds, but it’s not working , or error.

Code:

$(document).ready(function() {

    var $div_novospedidos = $('#div_novospedidos');
    $div_novospedidos.empty(); //Limpando a tabela
    //setTimeout(function(){ location.reload(); }, 30000);
    setTimeout(newRequests(), 30000);


    function newRequests() {
        //$div_novospedidos.load("database3.php", function(data, status){
        $.get("database3.php", function(data, status) {
            var dados_pedido = data;
            const obj = dados_pedido;

            function executa_new() {
                try {
                    var dados = JSON.parse(data);
                    console.log(dados);
                    $.each(dados, function(i, item) {
                        numeroPedido = item.doc_number;
                        nomeCliente = item.client_name;
                        horarioPedido = item.clock;
                        var newReq = $('<div class="panel panel-default col-6 col-lg-4 ">');
                        var cols = "";
                        cols += '<p>HORARIO: ' + horarioPedido + '</p></div>';
                        cols += '<p>PEDIDO: ' + numeroPedido + '</p></div>';
                        cols += '<p>Cliente: ' + nomeCliente + '</p></div>';
                        newReq.append(cols);
                        $("#div_novospedidos").append(newReq);
                    });
                } catch (e) {
                    if (typeof dados != 'undefined') {
                        alert('Ocorreu um erro durante a chamada ' + e);
                    } else {
                        var zeroReq = $('<div class="panel panel-default col-6 col-lg-4 "><h1>SEM NOVOS PEDIDOS</h1>');
                        $("#div_novospedidos").append(zeroReq);
                    }
                }
            }
            if (typeof dados != 'undefined') {
                alert("SEM PEDIDOS");
            } else {
                executa_new();
            }
        });
    }

});
  • There’s only one call setTimeout so it’ll never be every 30 seconds, and you’re using if (typeof dados != 'undefined') { out of function executa_new() where the dados is defined.

  • and what correction ?

  • Exchange the setTimeout for setInterval to see what happens. I don’t understand why one function inside the other.

  • Also I could not understand the idea of function executa_new inside ajax if it is not executed immediately or stored in a variable. It would be better to remove this function and leave only the code it has.

2 answers

1

You are using the function setTimeout which is a function that puts a maximum exception time for a given function, so I understand you want your function to be executed more than once, in which case the correct command is setInterval

Thus remaining:

$(document).ready(function() {

    var $div_novospedidos = $('#div_novospedidos');
    $div_novospedidos.empty(); //Limpando a tabela
    //setTimeout(function(){ location.reload(); }, 30000);
    setInterval(newRequests(), 30000);


    function newRequests() {
        //$div_novospedidos.load("database3.php", function(data, status){
        $.get("database3.php", function(data, status) {
            var dados_pedido = data;
            const obj = dados_pedido;

            function executa_new() {
                try {
                    var dados = JSON.parse(data);
                    console.log(dados);
                    $.each(dados, function(i, item) {
                        numeroPedido = item.doc_number;
                        nomeCliente = item.client_name;
                        horarioPedido = item.clock;
                        var newReq = $('<div class="panel panel-default col-6 col-lg-4 ">');
                        var cols = "";
                        cols += '<p>HORARIO: ' + horarioPedido + '</p></div>';
                        cols += '<p>PEDIDO: ' + numeroPedido + '</p></div>';
                        cols += '<p>Cliente: ' + nomeCliente + '</p></div>';
                        newReq.append(cols);
                        $("#div_novospedidos").append(newReq);
                    });
                } catch (e) {
                    if (typeof dados != 'undefined') {
                        alert('Ocorreu um erro durante a chamada ' + e);
                    } else {
                        var zeroReq = $('<div class="panel panel-default col-6 col-lg-4 "><h1>SEM NOVOS PEDIDOS</h1>');
                        $("#div_novospedidos").append(zeroReq);
                    }
                }
            }
            if (typeof dados != 'undefined') {
                alert("SEM PEDIDOS");
            } else {
                executa_new();
            }
        });
    }

});

A little more about the functions:

They are two interesting functions of Javascript, with them we can define a time interval that an event will happen.

The syntax of the two functions is practically identical. What changes is how they act.

Syntax:

window.setTimeout('funcao()', intervalo_em_milisegundos);
window.setInterval('funcao()', intervalo_em_milisegundos);

The two functions will call a second function passed by parameter in the range also determined by parameter.

Being the setTimeout() calling the function only once. While the setInterval() calls the function "infinitely" always in the same time interval.

To pause the function is used clearInterval(). Passing as parameter the name of your range.

Ex:

var intervalo = window.setInterval(lerolero, 1000);
function lerolero() {
    window.alert("Popup");
}
clearInterval(intervalo);

Source: http://rogeriolino.com/2006/12/19/javascript-settimeout-e-setinterval/

  • apparently the function is not running again after 30sec, put an Alert to be sure , and does not run again ....

  • You can give me more details, I tested here and all right.

  • for example, I put an Alert("test"); on the newRequests function, with the setInterval the way that Voce suggested, if I close this Alert, when the function runs again, it should not reopen ?

0


You should apply the desired range of way synchronous, that is, calling the function newRequests() only after the return of Ajax. The way you are doing, you can overload your server and even crash your browser.

So add a setTimeout() after the return of Ajax within the function you want to call again.

Another thing is to separate the functions. Each function has its own application, and in this case, it is best to leave them separate.

Your code would look like this.

$(document).ready(function() {
    var $div_novospedidos = $('#div_novospedidos');
    $div_novospedidos.empty(); //Limpando a tabela
    newRequests();
});

function newRequests() {
    //$div_novospedidos.load("database3.php", function(data, status){
    $.get("database3.php", function(data, status) {
        var dados_pedido = data;
        const obj = dados_pedido;

        setTimeout("newRequests()", 30000);

        if (typeof dados != 'undefined') {
            alert("SEM PEDIDOS");
        } else {
            executa_new();
        }
    });
}

function executa_new() {
    try {
        var dados = JSON.parse(data);
        console.log(dados);
        $.each(dados, function(i, item) {
            numeroPedido = item.doc_number;
            nomeCliente = item.client_name;
            horarioPedido = item.clock;
            var newReq = $('<div class="panel panel-default col-6 col-lg-4 ">');
            var cols = "";
            cols += '<p>HORARIO: ' + horarioPedido + '</p></div>';
            cols += '<p>PEDIDO: ' + numeroPedido + '</p></div>';
            cols += '<p>Cliente: ' + nomeCliente + '</p></div>';
            newReq.append(cols);
            $("#div_novospedidos").append(newReq);
        });
    } catch (e) {
        if (typeof dados != 'undefined') {
            alert('Ocorreu um erro durante a chamada ' + e);
        } else {
            var zeroReq = $('<div class="panel panel-default col-6 col-lg-4 "><h1>SEM NOVOS PEDIDOS</h1>');
            $("#div_novospedidos").append(zeroReq);
        }
    }
}
  • did not work , looped in filling the Divs with the wrong information.

  • @Rodrigobravo I forgot to put the function on setTimeout in quotes, like this: setTimeout("newRequests()", 30000);. Look now.

Browser other questions tagged

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