0

I am using javascript scroll pagination in my website. When a page is srcolled down, some items are loaded from database. The issue is that, sometime, scroll pagination is getting the same data from database. I have used async: false. But, it slowed the loading down. Javascript code:

if (check !== null) {
  $(window).scroll(function(ev) {

    if ($(window).scrollTop() + window.innerHeight >= $('#footer').offset().top) {
      var last_id = $(".item:last").data("id");

      loadData(last_id);
    };

  });
}

var dataCount = 1;

function loadData(last_id) {
  $.ajax({
    url: 'some/url/loader',
    type: "get",
    data: {
      id: last_id
    },
    // async: false,
    success: function(data) {
      if (data) {
        dataCount++;
        $('#div').append(data);
        check = 1;
      } else if (!data) {
        console.warn('no data');
        check = null;
      }
    }
  });
}

Loader method in a controller:

public function actionLoader() {
  $id = $_GET['id'];
  $cat_id = $_GET['cat_id'];
  $posts = SomeModel::getItems($id);

  if (!empty($posts)) {
    $q = $this - > renderPartial('view', array('data' => $posts));
    echo $q;
  }
}
dee.ronin
  • 1,040
  • 12
  • 22
Alisher Nasrullayev
  • 565
  • 1
  • 6
  • 22
  • Most probably `last_id = $(".item:last").data("id")` refers to the same ID. Try keeping track of what was already fetched with an arr and add another check to make sure JS doesn't fetched an already fetched ID – Adelin Jul 16 '18 at 12:25
  • ajax loaded content isn't in the DOM and so last id will be the last of the one that didnt load via ajax, hence you getting the same results – delboy1978uk Jul 16 '18 at 12:26
  • @delboy1978uk why ajax loaded content isn't in the DOM? he appends content to the DOM: `$('#div').append(data)` – RainDev Jul 16 '18 at 12:29
  • yes that's true, but because it wasn't there originally, you need to add fresh listeners, possibly by calling a function in the success method – delboy1978uk Jul 16 '18 at 12:30
  • Have a look at this question https://stackoverflow.com/questions/20246299/does-ajax-loaded-content-get-a-document-ready#20246940 – delboy1978uk Jul 16 '18 at 12:33
  • But there is `$(window).scroll()` event, not on dynamicaly added element... – RainDev Jul 16 '18 at 12:39

0 Answers0