2

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);
Moritz
  • 745
  • 1
  • 10
  • 32

3 Answers3

1

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()
});
james emanon
  • 11,185
  • 11
  • 56
  • 97
0

Try moving i++ below like this

success: function(datanew) {
        $("h1").text(i);
        var datarec = datanew.replace(/},]$/,"}]");
        //alert(datarec);
        var string  = json2html.transform(datarec,template);
        $(string).insertAfter($('.parent').last());
        i++;
    }
Fil
  • 8,225
  • 14
  • 59
  • 85
-1

Instead of:

$(string).insertAfter($('.parent').last())

Use:

$('.parent').append($(string))
Kaspar Lee
  • 5,446
  • 4
  • 31
  • 54
Mano
  • 1
  • 3