Jquery Ajax - Request problems every x seconds

Asked

Viewed 880 times

1

I am developing a web application that I use ajax to request from time to time to find out if there has been a new update, but my code does not work perfectly. I’m new to jquery and I’m having trouble implementing this feature. I got an example on the net but mine does not update the page.

The div I intend 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);
});

2 answers

3

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

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

Instead of that, use setTimeout when the return of Ajax 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();
});
  • giving the error: Uncaught Syntaxerror: Unexpected Dentifier on the line: $("#straws"). append('<a href="straws/detailsPallists? id='+i+'"><div class="item d-flex align-items-center"><div class="text"><font size="3"><center>Agent: '+data[i].agente.name+'</center></font><font size="2">Address: '+data[i].endereco.street+'</font></div></div></div></a>');

  • What would that be i in data[i]?

  • my input of an array of palettes

  • Added in the answer. Just make a loop.

2


The error is in the callback beforeSend. Like the Javascript is not finding the variable data and i, the Javascript ends the application and returns an error.

In case you are receiving one JSON, you must add this excerpt within the function done or the function of callback success (The most recommended).

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() {
    function getData() {
        $.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 the setTimeout.

  • it displays the following error in the browser console: Uncaught Syntaxerror: Unexpected token +=. Claiming d point and comma of the line: Let html += ' <div class="item d-flex align-items-center">';

  • @Carlosdiego corrected

  • Perfect @Valdeir, it worked. Mto obgdo

  • me another doubt, this way you realize that he blinks on the screen at each Update, because he cleans the page and then writes with the data of the new request, has to do this without this "blinking screen"?

  • @Carlosdiego has yes. I edited my answer.

  • now this coming array[0].

  • @Carlosdiego corrected.

Show 3 more comments

Browser other questions tagged

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