Martin Forsstedt
Martin Forsstedt

Reputation: 52

jQuery AJAX-request loading twice

I'm building an infinite Scroll which fetches results from a database when the scroller hits the bottom of the page. It's all working fine except for one small thing; it is fetching the results twice if I scroll down fast, as if the function is executed twice.

Here is my jQuery code:

$(window).scroll(function () {
    if($(window).scrollTop() == $(document).height() - $(window).height()) {
        var ID = $('.stbody:last').attr('id').match(/stbody(\d+)/)[1];
        $('#loader').show();
        $.ajax({
            url: "ajax_loadmore.php?lCom=" + ID,
            success: function (result) {
                if(result) {
                    $('#moreComments').append(result);
                    $('#loader').hide();
                } else {
                    $('#loader').hide();
                }
            }
        });
    }
});

Upvotes: 0

Views: 4918

Answers (2)

Joram van den Boezem
Joram van den Boezem

Reputation: 1102

As an addition to @JamWaffles answer:

You may just exit the function with return; instead of calling request.abort();. Otherwise you will make two AJAX requests for the same data = unnecessary load for your server. You should then, however, reset the request object with request = null; in the success and error callback.

PS. Would post this as a comment, but I can't.

Upvotes: 0

Bojangles
Bojangles

Reputation: 101543

Your AJAX requests are most likely queueing up behind one another, because they are asynchronous, even though JavaScript itself is mostly single threaded.

You can use the abort() method to make sure only one request runs at a time. You need to assign the jqXHR object returned by $.ajax() to a variable:

var request;

$(window).scroll(function () {
    if($(window).scrollTop() == $(document).height() - $(window).height()) {
        var ID = $('.stbody:last').attr('id').match(/stbody(\d+)/)[1];
        $('#loader').show();

        // Abort any currently executing request
        if(request) {
            request.abort();
        }

        // Make a new request
        request = $.ajax({
            url: "ajax_loadmore.php?lCom=" + ID,
            success: function (result) {
                if(result) {
                    $('#moreComments').append(result);
                    $('#loader').hide();
                } else {
                    $('#loader').hide();
                }
            }
        });
    }
});

abort() is a native function of the XMLHttpRequest object, however it is exposed by jQuery's jqXHR object, so can be called as usual.

Upvotes: 4

Related Questions