I'm having hard time figuring how to avoid duplicate ajax call for my infinite scroll javascript code.
It mostly works but sometimes i have 2 or 3 times the same ajax page call causing a sort of loop.
How to avoid this?
Thanks
//infiniteScroll
var currentPage = 1;
var intervalID = -1000;
var scroll = false;
$('document').ready(function(){
if ( scroll == true) {
if (window.location.pathname == "/" && window.location.search == "" && $('#items_container').length > 0) {
$('.pagination').hide();
intervalID = setInterval(checkScroll, 300);
}
};
})
function checkScroll() {
if (nearBottomOfPage()) {
currentPage++;
jQuery.ajax('?page=' + currentPage, {asynchronous:true, evalScripts:true, method:'get',
beforeSend: function(){
var scroll = false;
$('.spinner').show();
},
success: function(data, textStatus, jqXHR) {
$('.spinner').hide();
$('#items_container').append(jQuery(data).find('#items_container').html());
var scroll = true;
if(typeof jQuery(data).find('.item').html() == 'undefined' || jQuery(data).find('.item').html().trim().length == 0 || currentPage == 10){
clearInterval(intervalID);
}
},});
}
}
}
function nearBottomOfPage() {
return scrollDistanceFromBottom() < 450;
}
function scrollDistanceFromBottom(argument) {
return pageHeight() - (window.pageYOffset + self.innerHeight);
}
function pageHeight() {
return Math.max(document.body.scrollHeight, document.body.offsetHeight);
}
It looks like the checkScroll function is being called every 300 milliseconds, and it's possible that an AJAX request will take longer than that.
I see you've got the scroll variable, but you are only checking the value of it on the initial document load, which won't affect the timer.
I would suggest having a look at listening to the scroll event instead of creating a timer: jQuery docs. You could then do something like the following to prevent two ajax calls running:
var ajaxRunning = false;
function checkScroll() {
if (!ajaxRunning && nearBottomOfPage()) {
currentPage++;
ajaxRunning = true;
jQuery.ajax('?page=' + currentPage, {asynchronous:true, evalScripts:true, method:'get',
beforeSend: function(){
$('.spinner').show();
},
success: function(data, textStatus, jqXHR) {
$('.spinner').hide();
$('#items_container').append(jQuery(data).find('#items_container').html());
if(typeof jQuery(data).find('.item').html() == 'undefined' || jQuery(data).find('.item').html().trim().length == 0 || currentPage == 10){
clearInterval(intervalID);
},
complete: function() {
ajaxRunning = false;
}
},});
}
}
Set async to false, or create a variable like
var isLoading = false;
In before send set it to true. On success set it false again. And before sending the ajax call, check if isLoading isn't true. If it is, return out of the function or put a loop inside with a spinner, which will be checking for the isLoading value so it fires the ajax first after isLoading was set to false.
Example:
function checkScroll() {
if (nearBottomOfPage() && isLoading === false) {
currentPage++;
jQuery.ajax('?page=' + currentPage, {asynchronous:true, evalScripts:true, method:'get',
beforeSend: function(){
var scroll = false;
$('.spinner').show();
isLoading = true;
},
success: function(data, textStatus, jqXHR) {
$('.spinner').hide();
$('#items_container').append(jQuery(data).find('#items_container').html());
var scroll = true;
if(typeof jQuery(data).find('.item').html() == 'undefined' || jQuery(data).find('.item').html().trim().length == 0 || currentPage == 10){
clearInterval(intervalID);
isLoading = false;
}
},
});
}}}
Related
I have the following code which works fine for most cases, but the problem I am having is on mouse over . After you hover for 10 sec the content expands and then calls ajax. The Ajax is making calls 5 times instead of just once.
I am not sure why its keep calling 5 times. Can someone help me fix this so ajax call runs only once?
Here is my code snippet below and the full working fiddle demo is here
$(".previewCard-content").hide();
var timeo = null;
$("body").on("mouseenter", ".previewCard-showhide", function() { // Use rather mouseenter!
var $that = $(this); // Store the `this` reference
clearTimeout(timeo); // Clear existent timeout on m.Enter
timeo = setTimeout(function() { // Before setting a new one
$that.hide().closest('p').next(".previewCard-content").slideDown("slow");
/**************** AJAX CALL********************/
var LinkTextVal = $that.closest('.previewCard-b').find('.previewCardPageLink').text();
console.log(" LinkTextVal " + LinkTextVal);
var descPageName = LinkTextVal + ' | About';
if ($('#userID').val() !== '' && $('#userID').val() !== undefined && $('#userID').val() !== null) {
$.ajax({
url: '/localhost/biz/actions/searchBookmark' + '?cachestop=' + nocache,
type: "get",
data: {
bookmarkName: descPageName
},
success: function(response) {
if (response === true) {
$that.parents('.previewCard-b').find('.save a').addClass('saved');
$that.parents('.previewCard-b').find('.save a').addClass('active');
$that.parents('.previewCard-b').find('.save a').find(".action-text").text("Saved");
}
},
error: function(e) {
console.log('Unable to check if a bookmark exists for the user.');
}
});
}
/***************** END AJaX/SAVE BUTTON ************/
}, 1000);
}).on("mouseleave", ".previewCard-showhide", function() { // mouse leaves? Clear the timeout again!
clearTimeout(timeo);
});
$(".close-btn").on("click", function() {
var $itemB = $(that).closest(".previewCard-b");
$itemB.find(".previewCard-content").slideUp();
$itemB.find(".previewCard-showhide").show();
});
Mouse hover events happen every time the mouse moves over the element. You need is to have a boolean which checks if you have sent the AJAX Request or not, and if it hasn't send the AJAX request, else ignore the event.
$(".previewCard-content").hide();
var timeo = null;
var ajaxSent = false
$("body").on("mouseenter", ".previewCard-showhide", function() { // Use rather mouseenter!
var $that = $(this); // Store the `this` reference
clearTimeout(timeo); // Clear existent timeout on m.Enter
timeo = setTimeout(function() { // Before setting a new one
$that.hide().closest('p').next(".previewCard-content").slideDown("slow");
/**************** AJAX CALL********************/
var LinkTextVal = $that.closest('.previewCard-b').find('.previewCardPageLink').text();
console.log(" LinkTextVal " + LinkTextVal);
var descPageName = LinkTextVal + ' | About';
if ($('#userID').val() !== '' && $('#userID').val() !== undefined && $('#userID').val() !== null && !ajaxSent) {
ajaxSent = true;
$.ajax({
url: '/localhost/biz/actions/searchBookmark' + '?cachestop=' + nocache,
type: "get",
data: {
bookmarkName: descPageName
},
success: function(response) {
if (response === true) {
$that.parents('.previewCard-b').find('.save a').addClass('saved');
$that.parents('.previewCard-b').find('.save a').addClass('active');
$that.parents('.previewCard-b').find('.save a').find(".action-text").text("Saved");
}
},
error: function(e) {
console.log('Unable to check if a bookmark exists for the user.');
}
});
}
/***************** END AJaX/SAVE BUTTON ************/
}, 1000);
}).on("mouseleave", ".previewCard-showhide", function() { // mouse leaves? Clear the timeout again!
clearTimeout(timeo);
});
$(".close-btn").on("click", function() {
var $itemB = $(that).closest(".previewCard-b");
$itemB.find(".previewCard-content").slideUp();
$itemB.find(".previewCard-showhide").show();
});
I'm sorry the title might not make much sense. I'm not sure how to word what i'm doing.
I have a class that I add to elements that uses HTML5 data attributes to setup a refresh timer. Here is the current code.
$(document).ready(function () {
$('.refresh').each(function() {
var element = $(this);
var url = element.data('url');
var interval = element.data('interval');
var preloader = element.data('show-loading');
var globalPreloader = true;
if (typeof preloader === 'undefined' || preloader === null) {
}
else if (preloader != 'global' && preloader != 'true') {
globalPreloader = false;
}
(function(element, url, interval) {
window.setInterval(function () {
if (!globalPreloader)
{
$('#' + preloader).show();
}
$.ajax({
url: url,
type: "GET",
global: globalPreloader,
success: function (data) {
element.html(data);
if (!globalPreloader) {
$('#' + preloaderID).hide();
}
}
});
}, interval);
})(element, url, interval);
});
$.ajaxSetup({ cache: false });
});
Now I have elements that a user can click on the 'window' which removes it.
These elements can be tired to a timer that was set by the above code.
Code used to remove the element
$(".btn-close").on('click', function () {
var id = $(this).closest("div.window").attr("id");
if (typeof id === 'undefined' || id === null) {
} else {
$('#' + id).remove();
}
});
I need to now kill the timers created for the elements removed.
What is the best way to do this?
Not clear on how you clear them so I do them all here at the end.
$(document).ready(function () {
$('.refresh').each(function () {
var element = $(this);
var url = element.data('url');
var interval = element.data('interval');
var showLoading = element.data('show-loading');
var preloaderID = element.data('preloader-id');
if (typeof showLoading === 'undefined' || showLoading === null) {
showLoading = true;
}
(function (element, url, interval) {
var timerid = window.setInterval(function () {
if (showLoading) {
$('#' + preloaderID).show();
}
$.ajax({
url: url,
type: "GET",
global: showLoading,
success: function (data) {
element.html(data);
if (showLoading) {
$('#' + preloaderID).hide();
}
}
});
}, interval);
element.data("timerid",timerid );//add the timerid
})(element, url, interval);
});
$.ajaxSetup({
cache: false
});
$('.refresh').each(function () {
var timerId = $(this).data("timerid");
window.clearInterval(timerId);
});
});
Example: remove timer on a click
$('.refresh').on('click', function () {
var timerId = $(this).data("timerid");
window.clearInterval(timerId);
});
window.setIntervalreturns a handle for the timeout. You can use that to stop the timeout:
var handle = window.setInterval(function() {
window.clearInterval(handle);
}, 1000);
Hope that helps.
Here's a little demo of intervals and "interval assassins". It's a minimal example showing how you can clear intervals in a JavaScript-y way.
$('.start').click(function() {
var $parentRow = $(this).closest('tr')
var $stop = $parentRow.find('.stop')
var $val = $parentRow.children('.val')
// interval
var iid = setInterval(function() {
$val.text(+$val.text() + 1)
}, 10)
console.log(`New Target: ${iid}`)
// interval assassin
$stop.click(function() {
clearInterval(iid)
console.log(`Interval[${iid}] has been assassinated.`)
$(this).off('click')
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><button class="start">Start</button></td>
<td><button class="stop">Stop</button></td>
<td class="val">0</td>
</tr>
<tr>
<td><button class="start">Start</button></td>
<td><button class="stop">Stop</button></td>
<td class="val">0</td>
</table>
Just run the snippet to see a demo. Feel free to comment if you have any questions. You can set up multiple intervals by pressing start repeatedly and have them all be cleared at once with a single click of stop.
The following piece of code loads the next page, when the user scrolls to the bottom. However, sometimes it is repeating itself — when the user scrolls too rapidly, or scrolls whilst the AJAX is still being loaded.
Is there a way to prevent it from firing multiple times? So for example, nothing can be loaded while the AJAX is being called, or the AJAX can only be called once a second?
Any help would be great.
$(window).scroll(function() {
if( $(window).scrollTop() + $(window).height() == $(document).height()) {
if (firstURL !== null) {
$.get(firstURL, function(html) { // this gets called multiple times on erratic scrolling
firstURL = '';
var q = $(html).find('.post');
l = $(html).filter('div.bottom-nav');
if( l[0].childNodes.length > 0 ){
firstURL = l[0].children[0].getAttribute('href');
} else {
firstURL = null;
}
q.imagesLoaded( function() {
jQuery(".content").append(q).masonry( 'appended', q, true );
});
});
}
}
});
Just add a flag :
var ready = true; //Assign the flag here
$(window).scroll(function() {
//Check the flag here. Check it first, it's better performance wise.
if(ready && $(window).scrollTop() + $(window).height() == $(document).height()) {
ready = false; //Set the flag here
if (firstURL !== null) {
$.get(firstURL, function(html) { // this gets called multiple times on erratic scrolling
firstURL = '';
var q = $(html).find('.post');
l = $(html).filter('div.bottom-nav');
if( l[0].childNodes.length > 0 ){
firstURL = l[0].children[0].getAttribute('href');
} else {
firstURL = null;
}
q.imagesLoaded( function() {
jQuery(".content").append(q).masonry( 'appended', q, true );
});
}).always(function(){
ready = true; //Reset the flag here
});
}
}
});
I had a similar issue, that scrolling the window fired my function multiple times (manupulating my img slider's properties). To effectively deal with that matter you can defer the execution of scroll handler and use an additional 'page is being scrolled' flag to prevent multiple handler calls.
Check out the example below, you can surely addopt the approach to your case.
$(function()
{
var pageFold = 175; //scrolling threshold
var doScroll = false; //init
var timeoutScroll = 100; //delay
var windowScrolled = false; //initial scrolling indicatior
var windowScrolling = false; //current scrolling status indicator
//load next page handler
function loadNextPage()
{
if(windowScrolling != true)
{
//and do ajax stuff - your code
}
}
//check if page scrolled below threshold handler
function foldedBelow()
{
//nice scrolled px amount detection
return (Math.max($('body').scrollTop(), $('html').scrollTop()) > pageFold);
}
//actual scrolled handler
function doWindowScroll()
{
windowScrolled = true;
if(foldedBelow())
{
loadNextPage();
}
windowScrolling = false;
}
//deffered scroll hook
$(window).scroll(function(e){
windowScrolling = true;
clearTimeout(doScroll);
doScroll = setTimeout(doWindowScroll, timeoutScroll);
});
});
When I did something like this I implemented a timed scroll handler that calls a custom scrolled_to_bottom-event.
(function($, window, document){
"use strict";
var $document = $(document);
var $window = $(window);
var _throttleTimer = null;
var _throttleDelay = 100;
function ScrollHandler(event) {
//throttle event:
clearTimeout(_throttleTimer);
_throttleTimer = setTimeout(function () {
if ($window.scrollTop() + $window.height() > $document.height() - 400) {
console.log('fire_scrolled_to_bottom');
$document.trigger('scrolled_to_bottom');
}
}, _throttleDelay);
}
$document.ready(function () {
$window
.off('scroll', ScrollHandler)
.on('scroll', ScrollHandler);
});
}(jQuery, window, document));
And then in my object handling the reload I bound that event with a flag-check if it was already loading.
handler = {
...,
isLoading: false,
bind: {
var self = this;
$document.on('scrolled_to_bottom', function () {
if (self.isLoading) {
return;
}
self.nextPage();
});
}
nextPage(): function () {
var self = this;
this.isLoading = true;
$.ajax({
url: url,
data: self.searchData,
dataType: "json",
type: "POST",
success: function (json) {
// do what you want with respone
},
error: function (xhr, statusText, errorThrown) {
bootbox.alert('An error occured.');
},
complete: function () {
self.isLoading = false;
}
});
},
init: function () {
this.doInitStuff();
this.bind();
}
}
This way I seperated the concerns and can reuse the triggering nicely, and easily add functionality if other things should happen on reload.
Try storing some kind of data that stores whether the page is currently loading new items. Maybe like this:
$(window).data('ajaxready', true).scroll(function(e) {
if ($(window).data('ajaxready') == false) return;
if ($(window).scrollTop() >= ($(document).height() - $(window).height())) {
$('div#loadmoreajaxloader').show();
$(window).data('ajaxready', false);
$.ajax({
cache: false,
url: 'loadmore.php?lastid=' + $('.postitem:last').attr('id'),
success: function(html) {
if (html) {
$('#postswrapper').append(html);
$('div#loadmoreajaxloader').hide();
} else {
$('div#loadmoreajaxloader').html();
}
$(window).data('ajaxready', true);
}
});
}
});
Right before the Ajax request is sent, a flag is cleared signifying that the document is not ready for more Ajax requests. Once the Ajax completes successfully, it sets the flag back to true, and more requests can be triggered.
copied : jQuery Infinite Scroll - event fires multiple times when scrolling is fast
Here is my solution. You can get an idea and apply it to yours. Also to help others.
You can execute your method first with condition: if(loadInterval ===
null). That means if we already waited for 5 secs.
Assign loadInterval = setTimeout(), then nullify the variable after 5 secs.
Here is sample code.
//declare outside
var loadInterval = null;
// .....
// .....
$(window).scroll(function() {
if ($('.loadmore').isOnScreen() === true) {
//No waiting registered, we can run loadMore
if(loadInterval === null) {
// This console.log executes in 5 seconds interval
console.log('Just called ' + new Date());
// your code in here is prevented from running many times on scroll
// Register setTimeout() to wait for some seconds.
// The code above will not run until this is nullified
loadInterval = setTimeout(function(){
//Nullified interval after 5 seconds
loadInterval = null;}
, 5000);
}
}
});
I post here the IsOnScreen() plugin for jQuery (i found it on stackoverflow :)
$.fn.isOnScreen = function() {
var win = $(window);
var viewport = {
top: win.scrollTop(),
left: win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
I have the following part of a jQuery .ajax call. It checks every second I believe. How can I get to stop after 10 tries?
success: function (data) {
if (!data) {
setTimeout(function (inputInner) { CallIsDataReady(inputInner); }, 1000);
}
EDIT: I implemented one solution but the logging for the service call seems to stop after 2 times.
function CallIsDataReady(input) {
var timer;
var count = 0;
$.ajax({
url: "http://www.example.com/services/TestsService.svc/IsDataReady",
type: "GET",
contentType: "application/json; charset=utf-8",
data: input,
// dataType: "json",
success: function (data) {
if (!data) {
setTimeout(function(inputInner) {
CallIsDataReady(inputInner);
count++;
if (count == 10) {
clearInterval(timer);
count = 0;
}
}, 1000);
}
else {
console.log("data returned - calling callUpDateGrid");
//Continue as data is ready
callUpdateGrid(input);
}
},
error: function (jqXHR, textStatus, errThrown) {
console.log("AJAX call failed in CallIsDataReady");
console.log(errThrown);
}
});
Just assign your setTimeout to a variable, and use a counter, when it reaches 10, call clearTimeout()
user setInterval with a counter:
if (!data) {
var count = 0;
var interval;
interval = setInterval(function (inputInner) {
if (count === 10) {
clearInterval(interval);
return;
}
CallIsDataReady(inputInner);
count++;
}, 1000);
}
// global variable - should be outside your ajax function
var timer;
var count = 0;
....
success : function( data) {
if( ! data ) {
// don't know where you are getting inputInner. assuming its a global variable
timer = setInterval ( function ( inputInner ) {
CallIsDataReady(inputInner);
count++;
if ( count == 10 ) {
clearInterval(timer);
count = 0;
}
}, 1000);
}
}
Use an interval
var count = 0,
handler = setInterval(dostuff, 1000);
function dostuff(inputInner){
//CallIsDataReady(inputInner);
if(++count === 10)
clearInterval(handler);
}
http://jsfiddle.net/mGgLz/
However, you should never rely on the assumption that the ajax call always takes < 1000ms. Check the readyState on the XHR and make sure it's 4 before polling again.
here i am trying to achieve infinite scrolling but what happens when i am scrolling too fast it fire multiple ajax request with same parameter , which cause same data again n again.how overcome from this problem pls help.
(function( $ ){
$.fn.scrollPagination = function(options) {
var opts = $.extend($.fn.scrollPagination.defaults, options);
var target = opts.scrollTarget;
if (target == null){
target = obj;
}
opts.scrollTarget = target;
return this.each(function() {
$.fn.scrollPagination.init($(this), opts);
});
};
$.fn.stopScrollPagination = function(){
return this.each(function() {
$(this).attr('scrollPagination', 'disabled');
});
};
var itr = 2;
$.fn.scrollPagination.loadContent = function(obj, opts){
var target = opts.scrollTarget;
var mayLoadContent = $(target).scrollTop()+opts.heightOffset >= $(document).height() - $(target).height();
if (mayLoadContent){
if (opts.beforeLoad != null){
opts.beforeLoad();
}
$(obj).children().attr('rel', 'loaded');
$.ajax({
type: 'POST',
url: opts.contentPage+"?iteration="+itr,
data: opts.contentData,
success: function(data){
itr++;
$(obj).append(data);
var objectsRendered = $(obj).children('[rel!=loaded]');
if (opts.afterLoad != null){
opts.afterLoad(objectsRendered);
}
}
});
}
};
$.fn.scrollPagination.init = function(obj, opts){
var target = opts.scrollTarget;
$(obj).attr('scrollPagination', 'enabled');
$(target).scroll(function(event){
if ($(obj).attr('scrollPagination') == 'enabled'){
$.fn.scrollPagination.loadContent(obj, opts);
//alert(event.isPropagationStopped());
}
//event.stopPropagation();
//console.log(event.isPropagationStopped());
event.preventDefault();
});
//$.fn.scrollPagination.loadContent(obj, opts);
};
$.fn.scrollPagination.defaults = {
'contentPage' : null,
'contentData' : {},
'beforeLoad': null,
'afterLoad': null ,
'scrollTarget': null,
'heightOffset': 0
};
})( jQuery );
How about firing off the ajax every 10 times the scroll event is triggered?
$.fn.scrollPagination.init = function(obj, opts) {
var target = opts.scrollTarget;
$(obj).attr('scrollPagination', 'enabled');
target.scrollCount = 0;
$(target).scroll(function(event) {
this.scrollCount++;
if (this.scrollCount % 10 == 0) {
if ($(obj).attr('scrollPagination') == 'enabled') {
$.fn.scrollPagination.loadContent(obj, opts);
//alert(event.isPropagationStopped());
}
//event.stopPropagation();
//console.log(event.isPropagationStopped());
event.preventDefault();
}
});
}
I used to call my ajax function when the scroll reaches the bottom of the page.
function nearBottomOfPage() {
return $(window).scrollTop() > $(document).height() - $(window).height() - 200;
}
$(window).scroll(function(){
if (loading) {
return;
}
if(nearBottomOfPage()) {
loading=true;
page++;
$("#place_of_loading_image").show();
$.ajax({
url:'your source',
type: 'get',
dataType: 'script',
success: function() {
$("#place_of_loading_image").remove();
loading=false;
}
});
}
});