0

I am calling ajax call but when I am scrolling 2 times its calling duplicate ajax calls.. For two scrolls I am getting duplicate ajax call.can anyone help me how to rectify duplicate ajax call.

jQuery(function($){       
    $('#infscr-loading').hide();
    $(window).scroll(function() { //detect page scroll
        if($(window).scrollTop() == $(document).height() - $(window).height()) {
            var key = $(".tab-content div.active").attr("id"); 
            var offset = $(".tab-content div.active .movie_boot .movie-beta__item").length;
            var data1 = $("#yr").val();             
            url = "/loop-movies/?offset="+offset+'&key='+key+'&yr='+data1;
            $.ajax({
                type       : "post",
                url        : url,
                delay      : 500, 
                beforeSend : function(){
                    $('#infscr-loading').show();
                },
                success    : function(response) {   
                    $(".tab-content div.active .movie_boot").append(response);
                    $('#infscr-loading').hide();
                }
            });         
        }
    });
});
2
  • 1
    you have written ajax call on scroll of window so it will call as many times as you scroll Commented Mar 16, 2016 at 13:21
  • I suggest using infinite or endless plugins which are easy to use Commented May 17, 2017 at 13:19

2 Answers 2

1
var flag;
if (flag.readyState == 4 && flag.status == 200) {
  flag = $.ajax({
    type: "post",
    url: url,
    delay: 500,
    beforeSend: function() {
      $('#infscr-loading').show();
    },
    success: function(response) {
      $(".tab-content div.active .movie_boot").append(response);
      $('#infscr-loading').hide();
    }
  });
}
else{
   alert("AJAX is going on")
}

Demo Fiddle to show the working

Reference

Sign up to request clarification or add additional context in comments.

1 Comment

@GabrielBenamy ... ha ha... Always glad to hear that :)
0

For achieving that behaviour you don't need to rely on the onScroll event all that just with Vanilla Javascript and the IntersectionObserver API.

All you need to do is place elements and listen for when they become available in the screen and have a global variable (in your scenario) that is switched to hasMoreItems = true or hasMoreItems = false when it reached the end or it's loading

You can accomplish that with a few javascript & html lines and it's much more performant than listening for scroll events in the browsers

I recently put together an article about infinite scrolling and this specific behaviour here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.