hellomello
hellomello

Reputation: 8585

implementing infinite scrolling without displaying duplicate data

I wrote a simple script where I am using ajax $.get to get my data for infinite scrolling. The problem is, I am maybe scrolling faster than it is loading, causing it to load three times?

function last_msg_funtion() 
{ 
    var ID=$(".feed_container").last().attr("id");
    $.ajax({
        url: "ajax/pagination.php",
        type:"get",
        data: "p="+ID
    }).done(function(data){
    if (data != "") 
        {
            var $boxes = $(data); 
            //$(".feed_container:last").after(data); 
            $("#feed_main").append($boxes).masonry('appended',$boxes);

        }
});

$(window).scroll(function(){
    var mostOfTheWayDown = ($(document).height() - $(window).height())  - 300;
    if ($(window).scrollTop() >= mostOfTheWayDown)
    {
        //alert('test');
        last_msg_funtion();
    }
}

If I scroll all the way down, it takes a while to load. The data I'm returning in last_msg_function() is the AJAX $.get() where I'm getting images. However, it is loading triple the same data. Any idea to prevent this?

Thanks

Upvotes: 1

Views: 1924

Answers (2)

Gavin
Gavin

Reputation: 7944

You need to set a "searching" variable that is false when idle and true when searching, then use that to know when to initiate a new search.

var searching = false; // new variable

function last_msg_funtion() 
{ 
    if (!searching) { // only initiate a new ajax request if this variable is false
        searching = true; // set variable to true
        var ID=$(".feed_container").last().attr("id");
        $.ajax({
            url: "ajax/pagination.php",
            type:"get",
           data: "p="+ID
       }).done(function(data){
            searching = false; // set variable to false on success
            if (data != "") 
            {
                var $boxes = $(data); 
                //$(".feed_container:last").after(data); 
                $("#feed_main").append($boxes).masonry('appended',$boxes);

            }
       });
    }
}

Upvotes: 1

Alireza
Alireza

Reputation: 6848

When working with G+ and you scroll to the bottom of the page, G+ has little bit delay before fetching messages.
Use setInterval() It will solve your problem. Inside interval function call last_msg_funtion().

Upvotes: 0

Related Questions