Skip to main content

Data Load While Page Scrolling (infinite scroll) with jQuery PHP and MySQL

Infinity scroll is a way to load more data using Ajax request while page goes to scroll down. Now days this technique is mostly used by the most of the successful websites like Facebook, Google and Twitter. You will be see that on these web sites as long as you scrolling down the page loads more and more data or posts, that is called infinity scroll or endless scroll. Though it can be possible by using jQuery's jQuery.ajax or jQuery.load method but now days there are many jQuery plugins (like, Infinity Scroll, Infinite Ajax Scroll) are available to make it more easy. Today I am going to show you how we can turn a PHP and MySQL paginavigation based website into dynamic infinity scroll with jQuery Infinite Ajax Scroll plugin.


Live Demo Download

Database Structure

First we need to create a database table. Because, we need some large amount of data to make this demo up and run here I am using Sakila simple database's actor_info table. The structure of this table looks like....

CREATE TABLE `actor_info` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(45) NOT NULL,
  `last_name` varchar(45) NOT NULL,
  `film_info` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

DB Configuration

The config.php file is responsible for database connect. I also include a variable named $limit with value of 10. It is the number of content you want to show on per page. You can increase or decrease this number as you want.

# db configuration 
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', 'root');
define('DB_NAME', 'dbname');

$limit = 10; #item per page
# db connect
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die('Could not connect to MySQL DB ') . mysql_error();
$db = mysql_select_db(DB_NAME, $link);

PHP and HTML

Take a look at the PHP and HTML code, this PHP code retrieves data from MySQL database with simple pagination.

<?php
include('config.php');
$page = (int) (!isset($_GET['p'])) ? 1 : $_GET['p'];
# sql query
$sql = "SELECT * FROM actor_info ORDER BY id DESC";
# find out query stat point
$start = ($page * $limit) - $limit;
# query for page navigation
if( mysql_num_rows(mysql_query($sql)) > ($page * $limit) ){
  $next = ++$page;
}
$query = mysql_query( $sql . " LIMIT {$start}, {$limit}");
if (mysql_num_rows($query) < 1) {
  header('HTTP/1.0 404 Not Found');
  echo 'Page not found!';
  exit();
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>jQuery Load While Scroll</title>
</head>
<body>
<div class="wrap">
  <h1><a href="#">Data load while scroll</a></h1>

  <!-- loop row data -->
  <?php while ($row = mysql_fetch_array($query)): ?>
  <div class="item" id="item-<?php echo $row['id']?>">
    <h2>
      <span class="num"><?php echo $row['id']?></span>
      <span class="name"><?php echo $row['first_name'].' '.$row['last_name']?></span>
    </h2>
    <p><?php echo $row['film_info']?></p>
  </div>
  <?php endwhile?>

  <!--page navigation-->
  <?php if (isset($next)): ?>
  <div class="nav">
    <a href='index.php?p=<?php echo $next?>'>Next</a>
  </div>
  <?php endif?>
</div><!--.wrap-->
</body>
</html>

JavaScript part

In the JavaScript section we need to first include jQuery and Infinity Ajax Scroll library. In the second pert we need to call jQuery.ias method and configure it. Take a look on the comments

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery-ias.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    // Infinite Ajax Scroll configuration
    jQuery.ias({
      container : '.wrap', // main container where data goes to append
      item: '.item', // single items
      pagination: '.nav', // page navigation
      next: '.nav a', // next page selector
      loader: '<img src="css/ajax-loader.gif"/>', // loading gif
      triggerPageThreshold: 3 // show load more if scroll more than this
    });
  });
</script>

Comments

  1. Great tutorial really helpful, i needed something like to integrate into a mobile app i am creating, Is there any way i get separate the html part from the php so that i make the request let say from index.html and retrieve the data from process.php?

    ReplyDelete
    Replies
    1. If you want to retrieve data form other files or resources it is better to use ajax and json. You can take a look at this tutorial https://tutsplus.com/lesson/ajax/

      Delete
  2. Very helpful tutorial! Great job!

    ReplyDelete
  3. thank you very much

    ReplyDelete
  4. Hey! thank you vere much!.

    How doy you configured .htaccess for dinamic url?

    For me in http://mydomain.com/index.php works your code
    but in http://mydomain.com/wherever/ not works

    in htaccess I have this Rewriterule ^wherever/(.*)/ index.php
    and load the file but not take the page

    ReplyDelete
    Replies
    1. very helpful tutorial, but i am having the same problem. did you figure it out?

      Delete
  5. Good work, thank you very much.
    Could you make a tutorial for use this infinite scrolling with laravel 4 please?

    ReplyDelete
    Replies
    1. You welcome!
      If you use Laravel 4 Pagination it will work for you. just use pagination::simple

      Delete
    2. Hi.. how to use infinite ajax scroll in laravel.?

      Delete
  6. Hai how to use that code viewer which you have used to display codes...

    ReplyDelete
    Replies
    1. Im using pretty print syntax highlighter by Google. If you want to use this in you project visit
      http://net.tutsplus.com/tutorials/html-css-techniques/quick-tip-how-to-add-syntax-highlighting-to-any-project/
      Thanks!

      Delete
  7. Script works fine. Thank you very much!

    ReplyDelete
  8. Hi, I am facing problem with tabs structure i have tabs on left side of my page on each of them when i click respective content shows others hide. Now when i click on one tab i have content which has infinite scroll used when i scroll the page it goes across smoothly no problem with page no proper but when i go to some another tab on the left side and then i come back to this tab the page not getting load properly gets hanged with no pagination. Please help urgent.

    ReplyDelete
  9. Hi, great tutorial! I have this working but also need to have filters and sorting. I currently have the filters working without ajax so whenever a filter is selected it refreshes the whole page. I am struggling to find out how to have the filters work as well as the infinite scrolling. Can you provide any advice on how to approach this? Many thanks in advance!

    ReplyDelete
  10. Awesome! Just awesome! Thanks a lot, grettings from Brasil ;)

    ReplyDelete
  11. Very Nice! Thank you!

    ReplyDelete
  12. This comment has been removed by the author.

    ReplyDelete
  13. Thank you so much for this api . I've been looking for such a tuto to integrate the ias() plugin into my project.

    ReplyDelete
  14. One problem - It breaks the Back button!

    ReplyDelete
  15. This comment has been removed by the author.

    ReplyDelete
  16. how can i use this i different page?

    ReplyDelete
  17. it doesn't work with mobile chrome =(

    ReplyDelete
  18. hello, thank you for that explanation. I'm trying to implement a search form. and view content with this system. Unfortunately, if I change the query $sql
    example
    from
    $sql = "SELECT * FROM actor_info ORDER BY id DESC";
    to
    $sql = "SELECT * FROM actor_info WHERE name LIKE '%$name%' ORDER BY id DESC";
    only on the first page i see the filtered results, while, when it loads the second page, I see all

    ReplyDelete
    Replies
    1. same problem with me , do you figure it out ? .

      Delete
  19. Ca you explain how does it get $_GET['p'], and calculate $page?

    ReplyDelete
  20. Good work, thank you very much.

    ReplyDelete
  21. to xyz : yes, because u don't put LIMIT in your queries

    ReplyDelete
  22. good stuff! but it seems not working well with WHERE 2 conditions. any suggestion????

    ReplyDelete
  23. Hi , How can I code your nice tutorial in Codeigniter ?

    Thanks you in advance. :)

    ReplyDelete
  24. Thank you so much for your awesome guide. it is working like a magic.

    ReplyDelete
  25. I have the same problems as xyz above. I have a sql that shows products where category= $_GET['cat'] but as he describes when it loads page number 2 it shows everyone in my database. Can you tell me why?

    $limit = 15;
    $page = (int) (!isset($_GET['p'])) ? 1 : $_GET['p'];
    $catID = (int) $_GET['cat'];

    # sql query
    $sql = "Select * From tbl_produkter Where visa=1 and (kategoriID=$catID or kategoriID2=$catID or kategoriID3=$catID) Order by sort";
    # find out query stat point
    $start = ($page * $limit) - $limit;
    # query for page navigation
    if( mysql_num_rows(mysql_query($sql)) > ($page * $limit) ){
    $next = ++$page;
    }
    $query = mysql_query( $sql . " LIMIT {$start}, {$limit}");
    if (mysql_num_rows($query) < 1) {
    header('HTTP/1.0 404 Not Found');
    echo 'Page not found!';
    exit();
    }

    ReplyDelete
  26. Very good script.
    But I have a problem, it's in conflict with other jquery script... my main menu stop works. Can I do something to avoid the conflict?

    ReplyDelete
    Replies
    1. I changes the position of the script and now everything work well.

      Delete
  27. Great job, there is another one, it may help you too:
    Ajax Scroll Paging Using jQuery, PHP and MySQL
    http://www.bewebdeveloper.com/tutorial-about-ajax-scroll-paging-using-jquery-php-and-mysql

    ReplyDelete
    Replies
    1. Thanks a lot. This works in most major browsers

      Delete
  28. I have an issue with this script. Once I load items the javascript of the items (thumbnail zoom) doesnt work. Just with the already loaded items. Could you please help me?

    ReplyDelete
  29. not working with firefox in my case

    ReplyDelete
  30. Great! Can u just help with this: How can i remove hashtag from url? (/#/page?=1) and go just /page?=1. THANKS!

    ReplyDelete
  31. This post is very useful for us. Because we have a lot of
    tips and tricks from this post. Thank you for this amazing post share. I many
    tips about bd career as well. If you want to know more about a career sites, please visit our website.

    www.bd-career.com

    ReplyDelete
  32. Hi, nice scroll! :) However, I'm curious, how can I get this to work inside a div container?
    I posted a question on Stackoverflow, if anyone is able to help I would really appreciate it.
    Link: http://stackoverflow.com/questions/32607784/adding-ajax-infinity-scroll-inside-a-div

    ReplyDelete
  33. Why is it that when it comes to the end of the page, instead of loading on scroll, it displays a load more ?

    ReplyDelete
  34. Hello
    I have tried your system and tried to convert it into procedural but i face a problem with binding of parametters. What is the equivalent of that ? How to convert this into procedural

    $query->bindParam(':last_id', $last_id, PDO::PARAM_INT);
    $query->bindParam(':limit', $limit, PDO::PARAM_INT);
    $query->execute();

    ReplyDelete
  35. awesome plugin. . very easy to use than other jquery plugins found on the net

    ReplyDelete
  36. Obat Kanker Kolon Stadium 4 - Ace Maxs merupakan solusi terbaik untuk mencegah dan mengobati kanker kolon secara aman dan tanpa ada efek samping, BUKTIKAN bahwa ace maxs betul betul membasmi penyakit kanker kolon dengan cepat dan aman. baca juga
    jelly gamat gold g di apotik

    ReplyDelete
  37. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. Hello
      i try use your code in my wordpress site but every time I scrolling the page I get the same 10 items from DB you can see in fire bug:

      GET http://localhost/mydomain.com/index.php?p=2
      GET http://localhost/mydomain.com/
      GET http://localhost/mydomain.com/index.php?p=2
      GET http://localhost/mydomain.com/
      GET http://localhost/mydomain.com/index.php?p=2
      GET http://localhost/mydomain.com/

      the P parameter is on 2 every time, and i didnt have index.php page.

      Delete
  38. Hello
    i try use your code in my wordpress site but every time I scrolling the page I get the same 10 items from DB you can see in fire bug:

    GET http://localhost/mydomain.com/index.php?p=2
    GET http://localhost/mydomain.com/
    GET http://localhost/mydomain.com/index.php?p=2
    GET http://localhost/mydomain.com/
    GET http://localhost/mydomain.com/index.php?p=2
    GET http://localhost/mydomain.com/

    the P parameter is on 2 every time, and i didnt have index.php page.

    ReplyDelete
    Replies
    1. I have the same problem on my website. Furthermore when i scroll the bottom, page becomes frozen for 10-15 seconds. After that it shows the same 10 items.

      Delete
  39. I have read your blog its very attractive and impressive. I like it your blog.

    PHP Training in chennai | PHP Training Course

    PHP Training in chennai | Online PHP Course

    ReplyDelete
  40. Thank you so much
    is very simple and effective.
    i thinking that infinite scroll is more hard
    but if your tutorial is easy.
    Again, thank you - Team Mestre Search

    ReplyDelete
  41. I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you. I like play game five nights at freddy’s 4, game word cookies game , game hill climb racing 2 , hotmail login, and u? I hope people visit my website.

    ReplyDelete
  42. The blog or and best that is extremely useful to keep I can share the ideas of the future as this is really what I was looking for, I am very comfortable and pleased to come here. Thank you very much.
    animal jam | five nights at freddy's | hotmail login

    ReplyDelete
  43. Uses ajax call, so no need of reloading the page for each category selection.Ajax Dynamic Category Listing

    ReplyDelete
  44. Pleasant Information. We sharing this article content writing style is too good, this information very helpful for all us. As I want to read your blog article because they were going to more and more interesting to be a starting of lines to ending lines.
    SEO Training in Chennai
    SEO Course in Chennai

    ReplyDelete
  45. hi
    Am unable to view this tutorial .show some errors.

    ReplyDelete
  46. This comment has been removed by the author.

    ReplyDelete
  47. nice blog
    get best placement at VSIPL

    get digital marketing services
    seo network point

    ReplyDelete
  48. It’s nice and valuable information; really appreciate for the nice blog...!!
    Hi guyz click here Best SAP Course in Bangalore to get the best knowledge and details and also 100% job assistance hurry up...!!

    DO NOT MISS THE CHANCE…

    ReplyDelete
  49. Awesome! Education is the extreme motivation that open the new doors of data and material. So we always need to study around the things and the new part of educations with that we are not mindful.
    hadoop admin certification course

    ReplyDelete
  50. Its really helpful for the users of this site. I am also searching about these type of sites now a days. So your site really helps me for searching the new and great stuff.

    aws training in bangalore

    aws courses in bangalore

    aws classes in bangalore

    aws training institute in bangalore

    aws course syllabus

    best aws training

    aws training centers

    ReplyDelete
  51. This is the exact information I am been searching for, Thanks for sharing the required infos with the clear update and required points. To appreciate this I like to share some useful information.

    mulesoft training in bangalore

    mulesoft courses in bangalore

    mulesoft classes in bangalore

    mulesoft training institute in bangalore

    mulesoft course syllabus

    best mulesoft training

    mulesoft training centers

    ReplyDelete
  52. We as a team of real-time industrial experience with a lot of knowledge in developing applications in python programming (7+ years) will ensure that we will deliver our best in python training in vijayawada. , and we believe that no one matches us in this context.

    ReplyDelete
  53. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    top servicenow online training
    servicenow online training
    best servicenow online training

    ReplyDelete


  54. Well thats a nice article.The information You providied is good . Here is i want to share about dell boomi tutorial and Aws Training videos . Expecting more articles from you .

    ReplyDelete
  55. Hi, your article was of great help. I loved the way you shared the information, thanks.
    Amazing article, I highly appreciate your efforts, it was highly helpful. Thank you CEH Training ,CEH Certification, CEH Online Course, Ethicalhacking

    ReplyDelete
  56. Hi, This is your awesome article , I appreciate your effort, thanks for sharing us.
    cism training
    cism certification

    cisa training,
    cisa certification
    cisa exam

    ReplyDelete
  57. I found some useful information in your blog, it is awesome to read and highly informative.
    Salesforce Certification Australia   

    ReplyDelete
  58. Great post! I am actually getting ready to across this information, It’s very helpful for this blog. Also great with all of the valuable information you have Keep up the good work you are doing well.
    CRS Info Solutions Salesforce Admin Training   

    ReplyDelete
  59. I have recently visited your blog profile. I am totally impressed by your blogging skills and knowledge.

    SAP FICO Online Training

    SAP FICO Classes Online

    SAP FICO Training Online

    Online SAP FICO Course

    SAP FICO Course Online

    ReplyDelete
  60. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    mulesoft online training
    best mulesoft online training
    top mulesoft online training

    ReplyDelete
  61. Good Post! , it was so good to read and useful to improve my knowledge as an updated one, keep blogging.After seeing your article I want to say that also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.
    https://www.3ritechnologies.com/course/mean-stack-training-in-pune/

    ReplyDelete
  62. Excellant blog!!! I got to know more useful information by reading your blog. Thanks for posting this blog.

    best apache spark online course

    ReplyDelete
  63. Nice blog. I finally found great post here Very interesting to read this article and very pleased to find this site. Great work! Rajasthan Budget Tours

    ReplyDelete
  64. That was a nice blog and it is very interesting to read
    Please check our resources which will be helpful
    We provide best Best Selenium Training in Bangalore, automation testing with live projects. Cucumber, Java Selenium and Software Testing Training in Bangalore.
    Java Selenium Automation Training in Bangalore
    Online selenium training in India

    ReplyDelete
  65. Nice article I was really impressed by seeing this blog, it was very interesting and it is very useful for me.

    big data certification course in Bangalore
    Hadoop Training in bangalore

    ReplyDelete

  66. I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly.I want to share about Mulesoft training .

    ReplyDelete

  67. Firstly talking about the Blog it is providing the great information providing by you . Thanks for that .Hope More articles from you . Next i want to share some information about Salesforce training in Banglore .

    ReplyDelete

  68. Firstly talking about the Blog it is providing the great information providing by you . Thanks for that .Hope More articles from you . Next i want to share some Information about Salesforce training in Hyderabad .

    ReplyDelete
  69. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.
    Data Science
    Selenium
    ETL Testing
    AWS
    Python Online Classes

    ReplyDelete
  70. This is most informative and also this post most user friendly and super navigation to all posts.
    3D Scanning Services Near Me

    ReplyDelete
  71. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    top mulesoft online training

    ReplyDelete

Post a Comment

Popular posts from this blog

Multiple File Upload with Progress Bar using PHP & jQuery

Some days age I have created a post that deals with How we can upload file with progress bar using php and jQuery . Some of my readers asked me how we can upload multiple files with progress bar. In this post I am going to show you how we can upload multiple files with progress bar. We can upload multiple files with progress bar exactly same way as I shown previous. But we need to do some modification with our file upload form and our php script to handle multiple files.

Force File Download with PHP

If you want to control or track your downloadable contents then a force file downloader script can give you more option. Especially if you want make images or other stemming contents like music file (mp3, wav, ogg), video files (flv, mp4, ogg, 3gpp), css, JavaScripts or even a php file downloadable then you must need to use a force file downloader script. In this post I am going to share a simple but useful force file downloader script.

Multiple File Upload with PHP

Sometimes we need to allow our users to upload multiple file upload. On my previous post I was shown the basic of simple file upload with PHP. Today I am going to show you how to allow users to upload multiple files. It is almost similar like simple file upload but we need to do some modification with html markup and php code . multiple attribute is needed to add on the html markup. Major web browsers like Firefox, Chrome, Safari and IE 9+ support this attribute. Now I am going to show you how to upload multiple file with PHP and basic HTML form.