Alert being repeated through .each () ajax

1

I have the following jQuery:

$("#apagar-marcados").click(function(){
    var lista_marcados = document.getElementsByName('id_mensagem[]');
    $.each(lista_marcados, function(i, item){
        if ($(item).prop('checked')){
            $.ajax({
                type: "POST",
                url: BASE_URL + "ajax/remover_mensagem",
                data:{id_mensagem: $(item).val()}, 
                cache: false,

                success: function(){
                    alert('atualizado')
                }
            });                 
        }
    });
});

In this, I do the update via SQL in the database, until then, works perfectly. In this case, I have a listing with checkbox, which in turn, marked, with the click the delete button, will enter this action.

The problem is, that if I select 10 checkbox, alert('atualizado') 10x will appear, how do I make it appear only once?

    
asked by anonymous 19.11.2017 / 15:03

1 answer

4

You should consider sending only 1 ajax to the server and letting the server make changes to the database. If this application is large and you have many users sending N ajax in this way it can be cumbersome for the server to manage.

To send only 1 ajax you could do this:

$("#apagar-marcados").click(function() {
  var lista_marcados = document.getElementsByName('id_mensagem[]');
  var marcados = [].filter.apply(lista_marcados, function(item) {
    return item.checked;
  }).map(function(item) {
    return item.value;
  });

  $.ajax({
    type: "POST",
    url: BASE_URL + "ajax/remover_mensagem",
    data: {marcados: marcados},
    cache: false,
    success: function() {
      alert('atualizado')
    }
  });

});

But answering your question you can do this:

$("#apagar-marcados").click(function() {
  var items = $('[name="id_mensagem[]"]').get();
  var ajaxs = items.reduce(function(arr, item) {
    if (!item.checked) return arr;
    const ajax = $.ajax({
      type: "POST",
      url: BASE_URL + "ajax/remover_mensagem",
      data: {id_mensagem: item.value},
      cache: false
    });
    return arr.concat(ajax);
  }, []);

  $.when.apply($, ajaxs).done(function() {
    alert('Concluído!');
  });
});
    
19.11.2017 / 15:14