0

I've recently learned the basics of SQL, Ajax and (object oriented) PHP, which I've put to use by creating a user build feed of information. However, at present the feed only loads the 20 most recent posts in the database (since loading all of them at once would have a negative impact on the page load time).

I've decided that trying to implement a system of infinite-scrolling (similar the method used by Twitter and Facebook) would be the best solution to this problem, but I'm not entirely sure how to do this.

I know that the first thing I need is a function to tell whether the user has reached the bottom of the page. To do this, I've written the following simple JQuery:

  $(window).scroll(function() { 
    var scrollBottom = $(document).height() - $(document).scrollTop() - $(window).height(); 
    if(scrollBottom < 200) {
      // send Ajax request
    }
  });

This bit of code should work, but I am concerned about the risk of multiple Ajax requests being sent to the server if the user scroll multiple times before the feed of posts has been updated.

I gather that the next thing I need to do is send off an Ajax request. Naturally, the script which currently retrieves the first 20 posts in the database uses a line of php/SQL looking like

$query = "SELECT * FROM table DESC LIMIT 0,20";

I'm guessing that I need to replace this with something like

$query = "SELECT * FROM table DESC LIMIT " . $x . "," . $x+20;

and then create another script which keeps track of how many times the Ajax request has been sent off, and use this to determine the variable $x to ensure the correct results are fetched.

Finally I know I'd need to create some sort of callback function to display the posts that had been fetched.

Is this the correct (best) method to use to create a system of infinite scrolling? Also, how can I alter the jQuery to stop multiple requests being sent off?

John Smith
  • 349
  • 1
  • 12
  • if it works = correct. if not = incorrect –  Sep 12 '16 at 22:02
  • You might find this interesting: http://midnightprogrammer.net/post/Infinite-Scrolling-In-ASPNET-With-jQuery/ – Velocibadgery Sep 12 '16 at 22:03
  • `$query = "SELECT * FROM table DESC LIMIT " . $x . "," . $x+20;` should be `$query = "SELECT * FROM table DESC LIMIT " . $x . ", 20";` just saying, or you will miss some rows! – olibiaz Sep 12 '16 at 22:04
  • @Velocibadgery thats asp not php –  Sep 12 '16 at 22:04
  • Sorry, to define correct I mean is it the best way of solving this problem, or are the better alternatives. – John Smith Sep 12 '16 at 22:27

1 Answers1

0

Yes you are correct, what you are looking for is $query = "SELECT * FROM table DESC LIMIT " . $x . ", 20"; which should get the next 20 rows and prevent more from being gotten until $x is updated.

dalearn
  • 231
  • 5
  • 17