-1

I'm trying to refresh my div using an ajax call, but for some reason it only fires in the first click, what am i doing wrong.

the first time i click the button it do everything fine, after that nothing happens (the loading part the rest of the script works fine)

here is the code of my javascript:

$('.btn-filtrar').on('click', function(){
    let id = $(this).closest('tr').data('id');
    let filter_type = $(this).closest('tr').data('type');
    let sort_order = document.getElementById(filter_type +'_sort-order_' + id).value;
    //console.log(id, filter_type, sort_order);


    $.ajax({
        url: "index.php?route=module/eot_filter/saveFilter&token=<?php echo $token; ?>",
        type: "POST",
        data: {
                id:id,
                filter_type:filter_type,
                sort_order:sort_order
            },
        success: function (result) {

                $("#"+ filter_type +"").load(" #"+ filter_type +"");


            }           
        });


});
Rui Leming
  • 61
  • 10

2 Answers2

1

You have to add the selector parameter, otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content).

See http://api.jquery.com/on/#direct-and-delegated-events

$(document).on('click','.btn-filtrar' ,function(){
  let id = $(this).closest('tr').data('id');
  let filter_type = $(this).closest('tr').data('type');
  let sort_order = document.getElementById(filter_type +'_sort-order_' + id).value;
  //console.log(id, filter_type, sort_order);


  $.ajax({
    url: "index.php?route=module/eot_filter/saveFilter&token=<?php echo $token; ?>",
    type: "POST",
    data: {
      id:id,
      filter_type:filter_type,
      sort_order:sort_order
    },
    success: function (result) {
      $("#"+ filter_type +"").load(" #"+ filter_type +"");
    }           
  });
});
laruiss
  • 3,780
  • 1
  • 18
  • 29
Deepak A
  • 1,624
  • 1
  • 7
  • 16
1

I would suggest you to Click Here to get the better idea on why to use $(document).on("click", "YOUR SELECTOR") ... instead of $("YOUR SELECTOR").on("click",..).

So in your case, the code should be something like :

$(document).on('click','.btn-filtrar' ,function(){
  let id = $(this).closest('tr').data('id');
  let filter_type = $(this).closest('tr').data('type');
  let sort_order = document.getElementById(filter_type +'_sort-order_' + id).value;
  //console.log(id, filter_type, sort_order);

    $.ajax({
        url: "index.php?route=module/eot_filter/saveFilter&token=<?php echo $token; ?>",
        type: "POST",
        data: {
          id:id,
          filter_type:filter_type,
          sort_order:sort_order
        },
        success: function (result) {
          $("#"+ filter_type +"").load(" #"+ filter_type +"");
        }           
      });
    });
Jitendra Ahuja
  • 749
  • 3
  • 9
  • 22