$. post performs twice

Asked

Viewed 69 times

1

I made a code in Java in which I make requests in php and with the return of a json I populate my html, the problem is that at a certain moment I need to execute the Java code but I am not able to make it stop, the $.post is triggered at the click of a button, but I did find that $.post is called twice in 1 click. Note: I tried for Avascript with Return, but $.post is called again

 $(document).on('click', '#btn_filtrarAnuncio',function(evento){ 
    var combo = document.getElementById("busca_anuncio_categoria");
    var categoria = combo.options[combo.selectedIndex].value; 
    var comboEstado = document.getElementById("busca_anuncio_estado");
    var estado = comboEstado.options[comboEstado.selectedIndex].value; 
    evento.preventDefault();
    carregar(0, 3, categoria, 'Chamadas/listarAnuncios.php');
    document.getElementById('cardAnuncios').innerHTML = "";


    $(document).on('click', '#carregarMaisFiltro',function(){ 

        var init = (jQuery('.anunciosJsonFiltro').length);
        carregar(init, 3, categoria,'Chamadas/listarAnuncios.php')
    });
    function carregar(init, max, categoria, url){
        var dados = { init : init, max : max, categoria : categoria, estado : estado };
        if(init >= 3)
        {
            $('#img_loadBuscarAnuncio').fadeIn('slow');
            $('#cardContainer').css("opacity", 0.4);
        }
        $.post(url, dados, function (data) {
            $("#carregarMaisFiltro").last().remove();

            for(i = 0; i < data.dados.length; i++){
                var img = data.dados[i].img ? data.dados[i].img : "../anuncio-padrao.png";

            $("#cardAnuncios").append('<div class="anunciosJsonFiltro">'
                +'<a style="display: block; color: rgba(0,0,0,0.87);" href="#">'
                     +'<div style="box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12); overflow: hidden; margin-bottom: 6px;">'  
                         +'<div class="col s4 m4" style="padding: 0px; margin: 0px;">'
                            +'<div style="width: 100%; overflow: hidden;">'
                                +'<div style="display: inline-block; position: relative; right: -50%;">'
                                     +'<img src="img/anuncios/'+img+'" alt="user background" style="height: 150px; width: auto; position: relative; left: -50%; vertical-align: bottom;">'
                                 +'</div>'
                             +'</div>'
                         +'</div>'
                         +'<div class="col s8 m8 truncate-text" style="padding-left: 14px; padding-top: 8px; height: 150px;">'
                                 +'<span class="grey-text text-darken-4" style="font-size: 20px;">'+data.dados[i].nm_titulo+'</span>'
                                +'<br>'
                                +'<span class="grey-text">Anúncio criado por: '+data.dadosComplementares[i].nm_usuario+' em '+moment(data.dados[i].dt_criacao).format("DD/MM/YYYY")+'</span>'
                                +'<div class="star-result" style="margin-bottom: -10px;">'
                                     +'<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">'
                                     +'<style>'
                                         +'.checked {'
                                             +'color: orange;'
                                        +'}'
                                   +'</style>'
                                    +'<span class="fa fa-star checked"></span>'
                                     +'<span class="fa fa-star checked"></span>'
                                     +'<span class="fa fa-star checked"></span>'
                                     +'<span class="fa fa-star"></span>'
                                     +'<span class="fa fa-star"></span>'
                                 +'</div>'
                                 +'<br>'
                                 +'<i class="mdi-image-navigate-next cyan-text text-darken-2"></i>'
                                 +'<span class="cyan-text text-darken-2">'+data.dadosComplementares[i].categoria+'</span>'
                                 +'<br>'
                                 +'<i class="mdi-communication-location-on cyan-text text-darken-2"></i>'
                                +'<span class="cyan-text text-darken-2">'+data.dadosComplementares[i].bairro+', '+data.dadosComplementares[i].municipio+' - '+data.dadosComplementares[i].estado+'</span>'
                         +'</div>'
                     +'</div>'
                 +'</a>'
                 +'</div>');
            }

            if(data.dados.length > 0)
            {
                $("#cardAnuncios").append('<button id="carregarMaisFiltro" class="btn right" style="background-color: #0097a7;" type="submit" name="action"><center>Carregar mais</center></button>');
            }; 
            var conta = $(".anunciosJsonFiltro").length;

            if(conta == data.totalAnuncios+init) {
                // deveria parar aqui  < ------
                $("#carregarMaisFiltro").last().remove();
                $('#img_loadBuscarAnuncio').fadeOut('slow');
                $('#cardContainer').css("opacity", 1.0);
                $("#carregarMaisFiltro").hide();
            }
        }, "json");
    }

});

1 answer

2


You put this event inside another:

$(document).on('click', '#carregarMaisFiltro',function(){ 

    var init = (jQuery('.anunciosJsonFiltro').length);
    carregar(init, 3, categoria,'Chamadas/listarAnuncios.php')
});

Both events are calling the function that contains the $.post, then the function will be executed 2 times.

To fix this, just put this event outside the other and the function carregar() also to make it accessible for both events:

$(document).on('click', '#carregarMaisFiltro',function(){ 
  var init = (jQuery('.anunciosJsonFiltro').length);
  carregar(init, 3, categoria,'Chamadas/listarAnuncios.php')
});

$(document).on('click', '#btn_filtrarAnuncio',function(evento){ 
  var combo = document.getElementById("busca_anuncio_categoria");
  var categoria = combo.options[combo.selectedIndex].value; 
  var comboEstado = document.getElementById("busca_anuncio_estado");
  var estado = comboEstado.options[comboEstado.selectedIndex].value; 
  evento.preventDefault();
  carregar(0, 3, categoria, 'Chamadas/listarAnuncios.php');
  document.getElementById('cardAnuncios').innerHTML = "";
});

function carregar(init, max, categoria, url){
var dados = { init : init, max : max, categoria : categoria, estado : estado };
if(init >= 3)
{
    $('#img_loadBuscarAnuncio').fadeIn('slow');
    $('#cardContainer').css("opacity", 0.4);
}
$.post(url, dados, function (data) {
    $("#carregarMaisFiltro").last().remove();

    for(i = 0; i < data.dados.length; i++){
        var img = data.dados[i].img ? data.dados[i].img : "../anuncio-padrao.png";

    $("#cardAnuncios").append('<div class="anunciosJsonFiltro">'
        +'<a style="display: block; color: rgba(0,0,0,0.87);" href="#">'
             +'<div style="box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12); overflow: hidden; margin-bottom: 6px;">'  
                 +'<div class="col s4 m4" style="padding: 0px; margin: 0px;">'
                    +'<div style="width: 100%; overflow: hidden;">'
                        +'<div style="display: inline-block; position: relative; right: -50%;">'
                             +'<img src="img/anuncios/'+img+'" alt="user background" style="height: 150px; width: auto; position: relative; left: -50%; vertical-align: bottom;">'
                         +'</div>'
                     +'</div>'
                 +'</div>'
                 +'<div class="col s8 m8 truncate-text" style="padding-left: 14px; padding-top: 8px; height: 150px;">'
                         +'<span class="grey-text text-darken-4" style="font-size: 20px;">'+data.dados[i].nm_titulo+'</span>'
                        +'<br>'
                        +'<span class="grey-text">Anúncio criado por: '+data.dadosComplementares[i].nm_usuario+' em '+moment(data.dados[i].dt_criacao).format("DD/MM/YYYY")+'</span>'
                        +'<div class="star-result" style="margin-bottom: -10px;">'
                             +'<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">'
                             +'<style>'
                                 +'.checked {'
                                     +'color: orange;'
                                +'}'
                           +'</style>'
                            +'<span class="fa fa-star checked"></span>'
                             +'<span class="fa fa-star checked"></span>'
                             +'<span class="fa fa-star checked"></span>'
                             +'<span class="fa fa-star"></span>'
                             +'<span class="fa fa-star"></span>'
                         +'</div>'
                         +'<br>'
                         +'<i class="mdi-image-navigate-next cyan-text text-darken-2"></i>'
                         +'<span class="cyan-text text-darken-2">'+data.dadosComplementares[i].categoria+'</span>'
                         +'<br>'
                         +'<i class="mdi-communication-location-on cyan-text text-darken-2"></i>'
                        +'<span class="cyan-text text-darken-2">'+data.dadosComplementares[i].bairro+', '+data.dadosComplementares[i].municipio+' - '+data.dadosComplementares[i].estado+'</span>'
                 +'</div>'
             +'</div>'
         +'</a>'
         +'</div>');
    }

    if(data.dados.length > 0)
    {
        $("#cardAnuncios").append('<button id="carregarMaisFiltro" class="btn right" style="background-color: #0097a7;" type="submit" name="action"><center>Carregar mais</center></button>');
    }; 
    var conta = $(".anunciosJsonFiltro").length;

    if(conta == data.totalAnuncios+init) {
        // deveria parar aqui  < ------
        $("#carregarMaisFiltro").last().remove();
        $('#img_loadBuscarAnuncio').fadeOut('slow');
        $('#cardContainer').css("opacity", 1.0);
        $("#carregarMaisFiltro").hide();
    }
}, "json");
}
  • Blz friend I will test this way and I already give you a feedback, the strange thing is that the first time I use the function of the click of the search button works normal, only if I press this button again it happens to use the $.post 2 times

  • It is because by clicking the first time the second event does not exist, already in the second click it has already been created and will fire 2 times.

  • Good morning, I did this way that you suggested and it worked perfectly, thank you very much, I’m 3 days standing at this point you saved me

Browser other questions tagged

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