How To Implement Infinite Scroll Using JQuery, Ajax and PHP
You
may have looked profile feeds of well known social networking sites like FaceBook and LinkedIn. They are using infinite scroll to display latest feeds. When you reach at bottom of page it updates relative feeds and so on. It loads new content via Ajax
when the user has finished scrolling through the page’s existing content.
Now a days, Ajax infinite scroller takes places of traditional paginations. This technique also known as lazy scroll. One of my reader have requested tutorial of Ajax Infinite Scroller. In this post we will learn how to integrate simple infinite ajax scroller
.
index.php
ajax.index.php
js/
--jquery.min.js
css/
--style.css
By getting request parameters form ajax
, It creates HTML response to append in scroller.
1
2
3
4
5
6
7
|
<?php
if (!empty($_POST['page'])) {
sleep(1);
echo "<li class='marginbottom10'>Page - ".$_POST['page'].'</li>';
exit;
}
?>
|
Add <div>
having class cls-scroller
and include latest version of jQuery (Download jQuery). cls-loader
shows loading status.
1
2
3
4
5
6
7
8
|
<body>
<h2>Infinite AJAX scroller</h2>
<div class="cls-scroller">
<li>AJAX scroller Demo</li>
</div>
<div class="cls-loader">loading...</div>
<script type="text/javascript" src="js/jquery-3.1.0.min.js"></script>
</body>
|
Ajax Call
page
provides page number for database records.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<script type="text/javascript">
var page = 1;
$(document).ready(function() {
$(window).scroll(function() {
if ($(document).height() - w.height() == w.scrollTop()) {
$('.loading').show();
$.post('ajax.index.php', {page: page}, function(data, textStatus, xhr) {
page++;
$('.cls-scroller').append(data);
$('.loading').hide();
});
}
);
});
</script>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
<body>
<h2>Infinite AJAX scroller</h2>
<div class="cls-scroller">
<li>AJAX scroller Demo</li>
</div>
<div class="cls-loader">loading...</div>
<script type="text/javascript" src="js/jquery-3.1.0.min.js"></script>
</body>
<script type="text/javascript">
var page = 1;
$(document).ready(function() {
var w = $(window);
w.scroll(function() {
if ($(document).height() - w.height() == w.scrollTop()) {
$('.loading').show();
$.post('ajax.index.php', {page: page}, function(data, textStatus, xhr) {
page++;
$('.cls-scroller').append(data);
$('.loading').hide();
});
}
});
});
</script>
|
When user scrolls bottom of page, Ajax
call fetches data from database using ajax.index.php
. Reach me at with your queries, I will glad to help.
Koushik Basu
Will it stop when the count is over?
nik
How to change URL while loading data!!