1

I'm trying to use Laravel pagination with jQuery. At first when I click to another page, it will be fine. However, when I click again to another page the number of click events is multiplied. It keeps increasing when I click again and again.

$(document).on('click', '.pagination a', function(event) {
  console.log(event);
  event.preventDefault();

  $('li').removeClass('active');
  $(this).parent('li').addClass('active');

  var page = $(this).attr('href').split('page=')[1];
  fetch_data(page);
});

function fetch_data(page) {
  $.ajax({
    url: "/get_rows?page=" + page,
    success: function(data) {
      $('#table_rows').empty().html(data);
    }
  });
}

Console output:

enter image description here

1
  • From the bug behaviour it looks like you're re-binding event handler to elements which already have it when the AJAX call completes - although your JS code doesn't show this. To fix the problem, just use the single delegated event handler, and only call it when the page loads. Commented Oct 8, 2021 at 14:51

1 Answer 1

0

A workeround could be to do it like this:

$('.pagination a').unbind().on('click', function(event) {
  console.log(event);
  event.preventDefault();

  $('li').removeClass('active');
  $(this).parent('li').addClass('active');

  var page = $(this).attr('href').split('page=')[1];
  fetch_data(page);
});

function fetch_data(page) {
  $.ajax({
    url: "/get_rows?page=" + page,
    success: function(data) {
      $('#table_rows').empty().html(data);
    }
  });
}

EDIT: it seems that unbind() is deprecated, you can do the same with off()

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.