0

I need to update/change the AJAX call while scrolling the page. I tried this with the scroll handler, but it doesn't work.

var size = "8";
var from = "0";
var url = "mywebservice" + from + "&s=" + size;

$(document).scroll(function (e) {
  var url = "mywebservice" + from + "&s=" + size;
  if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
    ++size;
  }

  $.ajax({
    type: 'GET',
    url: url,
    data: { get_param: 'value' },
    dataType: 'json',
    success: function (data) {
      $.each(data, function (index, element) {
        var HTML ='<div>' + element.name + '</div>';
        $('#container').append(HTML);
      });
    }
  });
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Fuel89
  • 15
  • 5
  • What does your html look like? as you may not be scrolling the document but an element instead – George Mar 29 '17 at 10:07
  • 1
    Be very, *very* wary of using this logic. The `scroll` event can potentially fire once for *every pixel* you scroll. Therefore if you scroll down the page you could potentially flood your server with 1000+ requests. I'd strongly suggest you debounce the `scroll` event if you need this behaviour – Rory McCrossan Mar 29 '17 at 10:09
  • does not work means? Is the ajax is not being fired or there is any kind of error while triggering the ajax or the scroll itself is not being called. And my opinion you should place a setTimeout and cleartTimeout in scroll handler and inside that callback all stuff should reside [check this](http://stackoverflow.com/questions/7392058/more-efficient-way-to-handle-window-scroll-functions-in-jquery) – Abhisek Malakar Mar 29 '17 at 10:16
  • Means: after the scroll handler I got a white screen, no alerts or console.log to see – Fuel89 Mar 29 '17 at 10:19

1 Answers1

-1

Try using alert(size) on scroll handler. If it works then your code should work too. And i think you should assign the value of URL after the if condition. So that each time you scroll, condition will be checked and you might get incremented size if condition is true.

  • It's seems the scroll handler block my code, because the alert doesn't show – Fuel89 Mar 29 '17 at 10:17
  • Yup. Thats what i thought. It means you have done some mistake in scroll event. I was just showing you the way of code. Please always cross check by writing alert on every event. I think you will get to the answer as you know where you made mistake. I cant write code for you because i dont know the exact html. – Roushan Choudhary Mar 29 '17 at 10:21
  • It's just a div container where i append a div inside – Fuel89 Mar 29 '17 at 10:26
  • try only scroll event first. I mean go stepwise. First on scroll event alert some thing. then try alerting $(document).height() and every variable one by one. – Roushan Choudhary Mar 29 '17 at 10:32
  • So I tried, the only Issues is the scroll handler, if i set "click" all works well, i don't know why – Fuel89 Mar 29 '17 at 11:05