This is my first time trying to implement an infinite scroll with JQuery / Ajax. This is where I am currently:
<script>
$(document).ready(function() {
// see if we're at the bottom of the page to potentially load more content
$(window).on('scroll', scrollProducts);
function scrollProducts() {
var end = $("#footer").offset().top;
var viewEnd = $(window).scrollTop() + $(window).height();
var distance = end - viewEnd;
// when we're almost at the bottom
if (distance < 300) {
// unbind to prevent excessive firing
$(window).off('scroll', scrollProducts);
console.log('we reached the bottom');
$.ajax({
type: 'GET',
url: "foo/bar/2",
success: function(data) {
console.log("success!");
$('#container').append(data).fadeIn();
// rebind after successful update
$(window).on('scroll', scrollProducts);
}
});
}
}
});
</script>
I'd like to understand the correct way to update the page number in the url: foo/bar/2
.
I've read that due to the difference between synchronous and asynchronous calls you can't use a global variable but instead need a callback (although I'm failing to understand it). I've also seen a solution where someone updated the values of hidden fields and then referenced those, although that seems like an ugly workaround.
What is the correct or recommended way to handle page numbers in this situation, so that the number increases with each request until there are no more pages?