Sorin Vladu
Sorin Vladu

Reputation: 1788

jQuery post - why there are duplicate requests?

I have this code:

$(window).scroll(function () { 

    if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {

        var site_url = $("#site_url").val();
        var post_url = site_url+"index.php/ajax/get_more_users";
        $("#loading_more_users").show();
        var users_page = $("#users_page").val();


        //alert("y");
        $.post(post_url, {'page': users_page}, function(data){              
                //alert("x");
            $("#loading_more_users").hide();
            $("#left_members_collumn").append(data);
            $("#users_page").val(eval(Number(users_page)+1));


        });

   }
});

Anyone can tell me why the $.post are executed once, twice or three times when I scroll bottom? I get the duplicate content. The main function is executed fine, but I don't know why there are multiples ajax requests.

Thank you.

Upvotes: 0

Views: 1626

Answers (2)

William Seiti Mizuta
William Seiti Mizuta

Reputation: 7985

YOu will execute the ajax request every time you scroll because you bind this functions to $(window).scroll() function. If your if return true, then you will execute the ajax request.

To evict this, you can use the function onefunction from jquery:

$(window).one('scroll', function () { 

    if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {

        var site_url = $("#site_url").val();
        var post_url = site_url+"index.php/ajax/get_more_users";
        $("#loading_more_users").show();
        var users_page = $("#users_page").val();


        //alert("y");
        $.post(post_url, {'page': users_page}, function(data){              
            //alert("x");
            $("#loading_more_users").hide();
            $("#left_members_collumn").append(data);
            $("#users_page").val(eval(Number(users_page)+1));
        });
   }
});

Upvotes: 2

John Koerner
John Koerner

Reputation: 38077

The scroll is firing multiple times with criteria that satisfy your if condition. What you can do to prevent this is set a bool to indicate your are posting, so you don't post twice:

var isPosting = false;
$(window).scroll(function () { 

    if (!isPosting && $(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
        isPosting = true;
        var site_url = $("#site_url").val();
        var post_url = site_url+"index.php/ajax/get_more_users";
        $("#loading_more_users").show();
        var users_page = $("#users_page").val();


        //alert("y");
        $.post(post_url, {'page': users_page}, function(data){              
                //alert("x");
            $("#loading_more_users").hide();
            $("#left_members_collumn").append(data);
            $("#users_page").val(eval(Number(users_page)+1));
            isPosting = false;

        });

   }
});

Upvotes: 3

Related Questions