I have been following the tutorial for creating infinite scroll / lazy load.
https://www.youtube.com/watch?v=oi1S-BpoMQY&feature=youtu.be
I have everything working except that when I scroll then AJAX fires POST multiple times instead of 1.
$(document).ready(function() {
var page_num = 1;
load_page(page_num, false);
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
page_num++;
load_page(page_num, false)
}
});
});
function load_page(page_num, loading) {
if (loading == false) {
loading = true;
$.ajax({
url: 'action/post.php',
type: "post",
data: {
page_num: page_num
},
beforeSend: function() {
$('#ajax-loader').show();
return;
}
}).done(function(data) {
$('#ajax-loader').hide();
loading = false;
$("#dynamic-posts").append(data);
}).fail(function(jqXHR, ajaxOptions, thrownError) {
$('#ajax-loader').hide();
});
}
}
2
Answers
The problem appears to be in document.height - 100. I changed it to 50 and it started to work. Anything more than 80 breaks the scroll.
I observed that variable loading alway is false, because is send as parameters.
I moved the scope variable loading. It help send 1 ajax by time.