Clear previous request and perform new only with the last element with jQuery

Asked

Viewed 86 times

0

I’m having a question in jQuery that I developed, I’m populating the data in style "combobox" and the requests and answers are correct however, my problem is when I click again on my ".item-Carousel" and I make my GET requests it keeps the last club clicked and instead of just making a request with the last one it makes with all the old + the last one.

$('.item-carousel').click(function() {
    let club = $(this).attr('data-id');

    $.get('/api/year', {
        club: club
    }, function (src) {
        $('select[name=year]').empty();
        $('select[name=year]').append('<option value="0">Selecione</option>');

        $.each(src, function (key, value) {
            $('select[name=year]').append('<option value=' + value['id'] + '>' + value['name'] + '</option>');
        });
    });

    // Realiza a busca dos meses com base no ano
    $('select[name=year]').change(function () {
        let year = $(this).val();

        $.get('/api/months', {
            club: club,
            year: year
        }, function (src) {
            $('select[name=month]').empty();
            $("select[name=month]").append('<option value="0">Selecione</option>');

            $.each(src, function (key, value) {
                $('select[name=month]').append('<option value=' + value['id'] + '>' + value['name'] + '</option>');
            });
        });
    });

    // Gera a tabela das transações do mês
    $('select[name=month]').change(function () {
        let month = $(this).val();
        let year = $('select[name=year]').val();

        $.get('/api/balance', {
            month: month,
            year: year,
            club: club
        }, function (data) {
            $('#balance-money').empty();
            $('#month-balance').empty();

            $('#balance-money').append('R$ ' + data[0]['total']);

            $.each(data, function (key, value) {
                $('#month-balance').append(`
                    <tr>
                        <td><p class="text-center">` + value['client'] + `</p></td>
                        <td><p class="text-center">R$ ` + value['balance'] + `</p></td>
                        <td><p class="text-center"> ` + value['status'] + `</p></td>
                        <td><p class="text-center">` + value['created_at'] + `</p></td>
                    </tr>
                `);
            });
        });
    });
});

To be clear, I attach my requisitions that are being madeRequisições realizadas

  • uses cache: false within your $.get({ cache: false, club: club, year: year [...]

  • When you put one Event Handler inside another, whenever you fire the event will create a new instance of what is nested. Ex.: all that you call $('.item-carousel').click(function() { will create a new $('select[name=year]').change(function () { and accumulates, that is, the onchange will run multiple times.

1 answer

1


Don’t nest event handlers inside another, because it will accumulate these nested handlers.

For example, when placing:

$(elemento).click(function(){
   $(elemento).change(function(){
   }
});

Every time the click is called, will generate a new change, that is, in the first click will generate a change; in the second click will generate another change which will be fired 2 times and so on.

The correct thing would be to separate the manipulators, one outside the other:

$(elemento).click(function(){
});

$(elemento).change(function(){
}

Only that the event change precise of the variable club that is created within the event click, and separating the events into the variable club at the event change will be invalid. You would then have to make this variable have global scope.

Declare the variable club out, and assign value to it within the click:

let club;
$(elemento).click(function(){
   club = $(this).attr('data-id');
});

$(elemento).change(function(){
}

But we must also prevent change execute AJAX if variable club is worthless. For this you put AJAX inside a if:

let club;
$('.item-carousel').click(function() {
    club = $(this).attr('data-id');

    $.get('conecta.php', {
        club: club
    }, function (src) {
       console.log(src);
    });

});

 // Realiza a busca dos meses com base no ano
 $('select[name=year]').change(function () {
     let year = $(this).val();

      if(club){
        $.get('conecta.php', {
            club: club,
            year: year
        }, function (src) {
             console.log(src);
        });
      }
 });

 // Gera a tabela das transações do mês
 $('select[name=month]').change(function () {
     let month = $(this).val();
     let year = $('select[name=year]').val();

      if(club){
        $.get('conecta.php', {
            month: month,
            year: year,
            club: club
        }, function (data) {
          console.log(data);
        });
      }
 });

Browser other questions tagged

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