Search code examples
jqueryajaxjson2html

Content added twice though only looped once


I want to add more content to my feed making use of AJAX and it does add content - but it adds it twice. To exclude causes like the AJAX request being submitted two times I added the integer i. But i only equals 1 (as stated by my h1 element) if I scroll down.

The AJAX success function receives a json object (which I can see in the alert) which is then transformed to html twice (the same object and accordingly the same html). Do you have any idea why this problem occurs?

jQuery:

function loadMore()
{
    var i = 0;
    var accountpar = $(".parent").length;

    $.ajax({
        url: 'homemore.php',
        type: 'post',
        data: {
            'account':accountpar
        },
        success: function(datanew) {
            i++;
            var datarec = datanew.replace(/},]$/,"}]");
            var string  = json2html.transform(datarec,template);
            alert(string);
            $(string).insertAfter($('.parent').last());
        }
    });
    $(window).bind('scroll', bindScroll);
}

function bindScroll(){
    if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
        $(window).unbind('scroll');
        loadMore();
    }
}

$(window).scroll(bindScroll);

Solution

  • I'd try something like this. My sense tells me that its' capturing the 'by pixel' and firing more than once. You can download the debounce/throttle plugin and use that, and set it to like 250, or try this "once method"

    if using debounce (have to download the plugin)

    I re-read your post (after you updated), and you are binding twice: once like this:

    $(window).scroll(bindScroll);
    

    and again like this:

    $(window).bind('scroll', bindScroll);

    I feel this is a red flag here. after the re-read, I'd probably either just download the plugin and wrap this in a debounce ($(window).scroll(bindScroll);).


    $.debounce( 250, bindScroll ) 
    

    instead of this:

     $(window).bind('scroll', bindScroll);
    

    try this:

    $( window ).one( "scroll", function() {
         bindScroll()
    });