I’m trying to set up a custom infinite scroll with jQuery and some Ajax. This is what I have so far:
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
$.ajax({
type: "POST",
url: "posts/view/",
data: "",
success: function(results){
$(".container").after(results);
}
})
}
});
It all works fine and dandy, but what I’m struggling to visualize is how to get the next “set” or, “page” of data. I’m using PHP and in my function I’ll have something like getMore($page = 1). But how can I have jQuery keep track of what page it’s currently on, and know which page is next? Should I set up some sort of increment function inside of jQuery so that it pulls the URL (e.g. posts/page/1/) and then simply add 1 to the url it passes via Ajax?
I feel like I’m really overthinking this, is there an easier way?
Just use a page counter inside the scroll closure:
And change your server script according to the
pageparam you are passing.If there is nothing more to retrieve, just answer with an empty body.
By the way,
POSTis not suitable for retreiving data, useGETinstead.