ajax duplicating div

Asked

Viewed 634 times

2

The function $.ajax is working correctly, but the return of the data being entered inside the div <#exibeCep> is being duplicated when the user clicks several times on the button. I tried to use .remove(), e.preventDefault();, stopPropagation();, bind() and others, but nothing has prevented the duplicity of div. What can I put up to avoid doubling the div ?

<div id="exibeCep" class="conf_frete">  <h1>Escolha a opção do frete</h1>  </div>

    $('#buscafrete').click(function(e) { 


    e.preventDefault();
    e.stopPropagation();
    cep = $('#cep').val();
    $.ajax({
        type:'GET',
        url: "{% url 'get_frete' %}",
        dataType: "json",
        data: {
            data:cep,
            csrfmiddlewaretoken:'{{csrf_token}}',
        },        
        success: function(retorno){

            if(retorno['sedex_cod_error'] == -3 || retorno['pac_cod_error'] == -3){
                $('<label><input type="radio" name="zipcode" id='+'sedex'+' value='+'CEP de destino invalido'+'/>'+
                    'CEP de destino invalido.'+'</label>').appendTo('#exibeCep');
            }else
                {
                $('<label><input type="radio" name="zipcode" checked id='+'sedex'+' value='+retorno['Sedex']+'/>'+
                    retorno['Sedex']+' ( '+'Sedex'+' ) '+'</label>').appendTo('#exibeCep');
                $('<label><input type="radio" name="zipcode" id='+'sedex'+' value='+retorno['Pac']+'/>'+retorno['Pac']+' ( '+'Pac'+' ) '+'</label>').appendTo('#exibeCep');           
            } 
        },

        error: function(jqXHR, textStatus, errorThrown){
            //alert("FALHOU");
            console.log('Error');
            console.log(jqXHR);
            console.log(textStatus);
            console.log(errorThrown);
        },
    });

});

2 answers

4


Create a div to receive the Ajax response:

<div id="exibeCep" class="conf_frete">
    <h1>Escolha a opção do frete</h1>
    <div id="cepAjax"></div>
</div>

Then use it to show the answer Ajax:

success: function(retorno){
    $('#cepAjax').empty();
    //resto do seu código aqui, usando .appendTo('#cepAjax');

Following my suggestion above you will empty the Ajax response container before populating it with the elements generated from the new answer.


Or to prevent the button from being clicked several times:

$('#buscafrete').click(function(e) { 
   this.disabled = true;

You can rehabilitate it within the success/error to allow more than one search, and combine it with the first part of the answer.

Finally, I did a slight rewrite of your code, using the above suggestions and adding some comments:

$('#buscafrete').click(function(e) { 
    e.preventDefault();
    this.disabled = true; //desabilita o botão após clicado

    var cep = $('#cep').val(); //use "var" para não criar globais
    $.ajax({
        type:'GET',
        url: "{% url 'get_frete' %}",
        dataType: "json",
        data: {
            data:cep,
            csrfmiddlewaretoken:'{{csrf_token}}',
        },
        context: this, //passa a referência "this" do escopo atual para o "this" dos callbacks
        success: function(retorno){
            this.disabled = false; //reabilita botão de busca
            $('#cepAjax').empty(); //esvazia a div de resposta antes de re-popular

            var invalido = retorno['sedex_cod_error'] == -3 || retorno['pac_cod_error'] == -3;

            //refatorei algumas partes comuns do seu if/else para diminuir a repetição
            var $lblSedex = $('<label><input type="radio" name="zipcode" id="sedex"></label>');
            $lblSedex.find('#sedex').val(invalido ? 'CEP de destino invalido' : retorno['Sedex']);
            $lblSedex.append(invalido ? 'CEP de destino invalido.' : retorno['Sedex']+' ( Sedex )');
            $lblSedex.appendTo('#cepAjax');
            if (!invalido) {
                //Obs.: você tinha IDs duplicados aqui, o que é inválido (o radio do Pac também tinha ID "sedex") então o removi.
                //Verifique se a estilização e comportamento continuam OK
                $('<label><input type="radio" name="zipcode" value="'+retorno['Pac']+'">'+retorno['Pac']+' ( Pac ) </label>').appendTo('#cepAjax');
            }
        },
        error: function(jqXHR, textStatus, errorThrown){
            //alert("FALHOU");
            this.disabled = false; //reabilita botão de busca
            console.log('Error');
            console.log(jqXHR);
            console.log(textStatus);
            console.log(errorThrown);
        }
    });

});

You don’t have to follow the above code, it was just to demonstrate some possible improvements. If in the future you want to treat invalid Zip Codes in a completely different way from valid Zip Codes, it would be interesting to keep yours if/else original.

  • This will not prevent ajax from being sent multiple times.

  • From what I understand the duplication is in the UI, anyway I will improve the answer now that I saw the HTML.

  • It worked at first !!! Thanks for the help. Thanks :) I’ll study what you put in the code because I need to learn it there. Thanks even

  • @Ricardo without problems, can mark the answer as accepted? Thanks. =]

0

Instead of using the appendTo method, try using the . html() method Example:

$("#exibeCep").html('<label><input type="radio" name="zipcode" id='+'sedex'+' value='+'CEP
                     + 'de destino invalido'+'/>'+'CEP de destino invalido.'+'</label>');

Browser other questions tagged

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