metafizzy / infinite-scroll

📜 Automatically add next page
https://infinite-scroll.com
7.41k stars 1.74k forks source link

checkLastPage not working when retrieving JSON #906

Open Snoop9 opened 4 years ago

Snoop9 commented 4 years ago

Hello, I'm using Infinite Scroll with this code :

$container.infiniteScroll({
  path: function() {
    var pageIndex = this.pageIndex + 1;
    var url = jQuery('#posts').data('url');
    url = url+pageIndex;
    return url;
  },
  append: false,
  responseType: 'text',
});

$container.on( 'load.infiniteScroll', function( event, response ) {
  var data = JSON.parse( response );
  $container.append( data.content );
});

But, when "/getLastPost" url is returning a blank JSON, infinite scroll is not detecting that empty result and is still trying to load the next page.

How can I fix this ?

desandro commented 4 years ago

One solution is to set scrollThreshold: false when there is no more content to append.

$container.on( 'load.infiniteScroll', function( event, response ) {
  if ( !response || !Object.keys( response ).length  ) {
    // disable scroll load behavior if no response
    $container.data('infiniteScroll').scrollThreshold = false;
    return;
  }
  var data = JSON.parse( response );
  $container.append( data.content );
});
kabirsaheb commented 3 years ago

Event when my path function returns nothing. It still tries to fetch next page with path as "undefined"

page-load.js:55 GET http://localhost:3000/undefined 404 (Not Found)