Jquery Ajax - Problems requesting every x seconds

1

I'm developing a web application that I use ajax to do from time to time to see if there was a new update, but my code does not work perfectly. I'm new to jquery and I'm having trouble implementing this functionality. I took an example on the net but my does not update the page.

The div I want to update:

<div id="palhetas" class="card-body no-padding">
                    #{list items:palhetas, as:'p'}
                    <div class="item d-flex align-items-center">
                        <input type="hidden" name="palheta.id" value="${p?.id}" />
                        <div class="text">
                            <a href="#"> <a href="javascript:void(0)" class="torre">
                                    <input type="hidden" name="palheta.id" value="${p.id}" /> <font
                                    size="3">Agente: ${p.agente.nome}</font>
                            </a><font size="2"> Endereço: ${p.endereco.rua} </font><br>
                            <font size="2"> Situação: ${p.situacao} </font>
                        </div>
                    </div>
                    #{/list}
                </div>

Ajax script

$(document).ready(function() {
    function getData() {
        $.ajax({
            url: "/Services/listarPalhetas",
            beforeSend: function() {$("#palhetas").empty();$("#palhetas").append(<a href="palhetas/detalhesPalhetas?id='+i+'"><div class="item d-flex align-items-center"><div class="text"><font size="3"><center>Agente: '+data[i].agente.nome+'</center></font><font size="2">Endereço: '+data[i].endereco.rua+'</font></div></div></a>');}                    
        }).done(function(data) {
            $("#palhetas").empty();         
            $("#palhetas").append(data);
        });
    }
    getData();
    setInterval(getData, 5000);
});
    
asked by anonymous 20.02.2018 / 00:59

2 answers

2

The error is in the callback event beforeSend . Since JavaScript is not encountering the variable data and i , JavaScript ends the application and returns an error.

If you are receiving a JSON , you should add this snippet inside the done function or the callback function success / p>

Example:

<div id="palhetas"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><script>$(document).ready(function(){functiongetData(){$.ajax({/*URL*/url:"index2.php",

            /* Retorna os dados no formato JSON */
            dataType: "json",

            /* Aciona esse evento antes da requisição */
            beforeSend: function() {
                //$("#palhetas").empty();
            },

            /* Aciona essa evento quando há sucesso da requisição */
            success: function(data) {

                $("#palhetas").html("");

                for (let i = 0; i < data.length; i++) {
                    /* Cria o html */
                    let html   = '<a href="palhetas/detalhesPalhetas?id='+i+'">';
                        html  += '   <div class="item d-flex align-items-center">';
                        html  += '       <div class="text">';
                        html  += '           <font size="3"><center>Agente: '+data[i].agente.nome+'</center></font>';
                        html  += '           <font size="2">Endereço: '+data[i].endereco.rua+'</font>';
                        html  += '       </div>';
                        html  += '   </div>';
                        html  += '</a>';

                    /* Inclui o HTML na variável indicada */
                    $("#palhetas").append(html);
                }
            },

            /* Aciona o evento ao finalizar a requisição */
            complete: function() {
                setTimeout(getData, 5000);
            }
        });
    }

    getData();
});
</script>
  

As remembered by the user DVD , you can also use setTimeout .

    
20.02.2018 / 01:10
3

Do not use setInterval . The setInterval is an uninterrupted timer and will be sending requests to Ajax without waiting for the previous request to be terminated.

  

When using setInterval , open your console (F12) on the "Network" tab and see the   bottleneck of almost simultaneous requisitions. Consequences: Slower site, unnecessary bandwidth consumption, server stress etc ... With setTimeout , it will only be 1 request every 5 seconds (time set to 5000)

Instead, use setTimeout when the Ajax return is complete:

$(document).ready(function() {
    function getData() {
        $.ajax({
            url: "/Services/listarPalhetas",
            beforeSend: function(){
               $("#palhetas").empty();
            },
            success: function(data)
                for(var i=0; i<data.length; i++){
                   $("#palhetas").append('<a href="palhetas/detalhesPalhetas?id='+i+'"><div class="item d-flex align-items-center"><div class="text"><font size="3"><center>Agente: '+data[i].agente.nome+'</center></font><font size="2">Endereço: '+data[i].endereco.rua+'</font></div></div></a>');
                }
            },
            complete: function(){
               setTimeout(getData, 5000);
            }
        });
    }
    getData();
});
    
20.02.2018 / 01:19