Thursday, April 12, 2012

Disable/enable jQuery click event to avoid multiple POST requests

I have a webpage that shows some news, and a button that when is clicked shows older news doing an AJAX call to the server.



The problem is that if people click too fast, the request is done twice, therefore, I receive 2 equal responses.




  • #mas-noticias-footer is the id of the button that displays older news


  • .noticias-list is the class asigned to each new, using .length I get
    the number of news displayed, and POST that number to a PHP file that
    does a SQL query using LIMIT(numItems,3) (I get 3 news at a time).


  • #noticias-display is the ul that contains the news




This is the code



$(document).ready(function() {
$("#mas-noticias-footer").on('click',function() {
var numItems = $('.noticias-list').length;
$.ajax({
type: "POST",
url: "mas-noticias.php",
data: "num-noticias="+numItems,
success: function(data) {
$('#noticias-display').append(data);
}
});
});
});


I have tried using off() and unbinding the event at the beginning of the on callback, to avoid the multiple calls (that works), the problem is when I delegate the event using on() at the end of the callback, I can't make it work.





No comments:

Post a Comment