I’m building an infinite Scroll which fetches results from a database when the scroller hits the bottom of the page. It’s all working fine except for one small thing; it is fetching the results twice if I scroll down fast, as if the function is executed twice.
Here is my jQuery code:
$(window).scroll(function () {
if($(window).scrollTop() == $(document).height() - $(window).height()) {
var ID = $('.stbody:last').attr('id').match(/stbody(\d+)/)[1];
$('#loader').show();
$.ajax({
url: "ajax_loadmore.php?lCom=" + ID,
success: function (result) {
if(result) {
$('#moreComments').append(result);
$('#loader').hide();
} else {
$('#loader').hide();
}
}
});
}
});
As an addition to @JamWaffles answer:
You may just exit the function with
return;instead of callingrequest.abort();. Otherwise you will make two AJAX requests for the same data = unnecessary load for your server. You should then, however, reset the request object withrequest = null;in the success and error callback.PS. Would post this as a comment, but I can’t.