Reputation: 25
The Ajax function of jQuery is working properly, but the return of the data being inserted into the div <# exibeCep>
being duplicated when the User clicks the button several times.
I tried using remove()
, e.preventDefault()
, StopPropagation()
, bind()
and others but nothing prevented the duplication of the div
.
What did I post to avoid duplicating the div?
HTML:
<div id="exibeCep" class="conf_frete">
<h1>Escolha a opção do frete</h1>
</div>
JavaScript:
$('#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);
},
});
});
Upvotes: 0
Views: 83
Reputation: 15609
To avoid double clicks from the user I normally add a class, for example is-loading
, and then check for that class. If it exists do nothing and return. Then in success
I remove the class.
Example
$('#buscafrete').click(function(e) {
if($(this).hasClass('is-loading')) {
// Do nothing.
return;
}
$(this).addClass('is-loading');
$.ajax({
},
success: function(retorno){
$(this).removeClass('is-loading');
});
}
Upvotes: 1
Reputation: 186
This is not solution of your problem but this can be helpful to you. What you can do is handle ajaxstart and ajaxstop method and in those you can enable and disable button so that ultimately you are restricting user to click inbetween...So user can not click and your data will not ne redundant...
Upvotes: 1