IIDenverII
IIDenverII

Reputation: 63

Stop .ajax from double loading content

I have the following code that loads content when a user scrolls to the bottom of the page. The problem is that if one scrolls too fast it double loads the content. What ways can I change my code to prevent this?

$(window).scroll(function(){
    if($(window).scrollTop() == $(document).height() - $(window).height()){
        $('div#ajaxResults').show();
        $.ajax({
            url: "ajax/home.php?last_id=" + $(".postitem:last").attr("id"),
            success: function(html){
                if(html){
                    $("#messages").append(html);
                    $('#ajaxResults').hide();
                }else{
                    $('#ajaxResults').html('<center>None.</center>');
                }
            }
        });
    }
});

I need for the solution to work multiple times. This script loads the next 5 messages, but there may be hundreds of messages that could be loaded. It is supposed to work in the same way that facebook or twitter loads updates.

Upvotes: 4

Views: 1132

Answers (3)

IIDenverII
IIDenverII

Reputation: 63

SOLUTION:

$(window).scroll(function(){
    if($(window).scrollTop() == $(document).height() - $(window).height()){
      var lastid = $(".postitem:last").attr("id");
        $('div#ajaxResults').show();
        $.ajax({
            url: "ajax/home.php?last_id=" + $(".postitem:last").attr("id"),
            success: function(html){
                if(html){
                    if(lastid == $(".postitem:last").attr("id")){
                    $("#messages").append(html);
                    $('#ajaxResults').hide();
                            }
                }else{
                    $('#ajaxResults').html('<center>None.</center>');
                }
            }
        });
    }
});

Add a variable that checks the lastid before the ajax is loaded, then only append html if the variable == the document last id. This way if ajax has already loaded, the two will not be equal and the update won't be posted.

Upvotes: 1

Sid
Sid

Reputation: 7631

Can you set a variable that stores the timestamp it was called and if it's within a few milli-seconds then doesn't call again? Kind of hack-ish but might do the trick. Obviously this isn't really solving the problem as that seems to be with how the scroll event is being triggered.

Upvotes: 0

kendaleiv
kendaleiv

Reputation: 5813

Try adding $(this).unbind('scroll'); inside the if block, assuming you do not want the ajax request to run more than once. Don't put it in the $.ajax success callback though, since it may fire more than 1 ajax request this way.

http://api.jquery.com/unbind/

Upvotes: 0

Related Questions