skip to Main Content

I have been following the tutorial for creating infinite scroll / lazy load.
https://www.youtube.com/watch?v=oi1S-BpoMQY&feature=youtu.be

I have everything working except that when I scroll then AJAX fires POST multiple times instead of 1.

$(document).ready(function() {
var page_num = 1;
load_page(page_num, false);

$(window).scroll(function() {
    if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
        page_num++;
        load_page(page_num, false)
    }
  }); 
});


function load_page(page_num, loading) {
if (loading == false) {
    loading = true;
    $.ajax({
        url: 'action/post.php',
        type: "post",
        data: {
            page_num: page_num
        },
        beforeSend: function() {
            $('#ajax-loader').show();
            return;
        }
    }).done(function(data) {
        $('#ajax-loader').hide();
        loading = false;
        $("#dynamic-posts").append(data);
    }).fail(function(jqXHR, ajaxOptions, thrownError) {
        $('#ajax-loader').hide();
    });
 }
}

2

Answers


  1. Chosen as BEST ANSWER

    The problem appears to be in document.height - 100. I changed it to 50 and it started to work. Anything more than 80 breaks the scroll.


  2. I observed that variable loading alway is false, because is send as parameters.
    I moved the scope variable loading. It help send 1 ajax by time.

    $(document).ready(function() {
    var page_num = 1;
    var loading = false;
    load_page(page_num);
    
    
    $(window).scroll(function() {
        if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
            page_num++;
            load_page(page_num)
        }
      }); 
    });
    
    
    function load_page(page_num) {
    if (loading == false) {
        loading = true;
        $.ajax({
            url: 'action/post.php',
            type: "post",
            data: {
                page_num: page_num
            },
            beforeSend: function() {
                $('#ajax-loader').show();
                return;
            }
        }).done(function(data) {
            $('#ajax-loader').hide();
            loading = false;
            $("#dynamic-posts").append(data);
        }).fail(function(jqXHR, ajaxOptions, thrownError) {
            $('#ajax-loader').hide();
            loading = false;
        });
     }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search