ajax duplicating div

2

The $.ajax function is working correctly, but the return of the data being inserted into the div is being duplicated when the user clicks the button several times. I tried to use .remove() , e.preventDefault(); , stopPropagation(); , bind() and others, but nothing prevented duplicity from div . What can I put to avoid duplicating 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);
        },
    });

});
    
asked by anonymous 18.02.2014 / 19:06

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 you will use it to display the Ajax response:

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 response.

Or to prevent the button from being clicked multiple times:

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

You can re-enable it within success / error to allow more than one search, and combine it with the first part of the response.

Finally, I did a slight rewrite of your code, using the suggestions above 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 do not have to follow the code above, just to demonstrate some possible improvements. If in the future you want to treat invalid ZIP codes in a completely different way than valid ZIP codes, it would be interesting to keep your% of% /% with original%.

    
18.02.2014 / 19:10
0

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

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