I have an endless scroll application in PHP and jQuery. This my javascript:
var base_url = window.location.origin;
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
var offset = $(".badge-item").length;
console.log(offset);
$.ajax({
url : base_url+'/index.php/display/jQuery_movies',
type : "post",
data : { offset_cnt : offset },
datatype : 'html',
success : function(response){
$("#badgesWrapper").append(response);
offset = offset+12;
},
error :function(){
alert("failure");
$("#result").append('Error Occurred while fetching data.');
}
});
}
});
This is my php (using CodeIngiter):
function jQuery_movies(){
$this->load->model('Model_display');
$offset = $this->input->post('offset_cnt',TRUE);
$result = $this->Model_display->fetch_movies($offset,$limit=12,$method='ajax');
echo $result;
}
As designed, the objective is to count the number of occurences of a class $(".badge-item")
and use that information to determine the offset for querying the database. The php loads initially loads a page of 12 badge-items when the user first hits the page. As the user scrolls down and gets close to the end another 12 badge-items should load. All is working fine except for the value of offset not updating properly. Batches of 12 are being loaded twice, sometimes as often as four times according to the console.log. Also according to the console.log offset
is not registering smoothly. That variable will jump at times going from 12, 24, 48, 72, 96 instead of 12, 24, 36, 48, 60, 72, 84, 96
Is there a better method for this jQuery script to work?