If you have lots of data and displaying the whole data in one time is very costly. There comes to approach one is lazy loading and another is pagination.
Here we are going to discuss the lazy loading in PHP, MySQL and Ajax. In lazy loading user can keep scrolling and keep getting the data until the whole data completes. Just like we quora and facebook do, User keep scrolling and post keep coming.
Mysql QueryClick here to download demo code
1
2
3
4
5
6
|
CREATE TABLE IF NOT EXISTS `post` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`image` varchar(150) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=247 ;
|
db.php
1
2
3
4
5
6
|
<?php
$con = new mysqli('localhost', 'root', '', 'demo');
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
?>
|
index.php
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
<style>
.posts { height: 100%; overflow: auto; width: 100%; }
.loading { color: green; }
li {font-size:20px;}
#loading { display:none; color:green; font-size:20px; }
</style>
<div class="posts">
<ol id="results"></ol>
</div>
<span id="loading">Loading Please wait...</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(function() {
loadResults(0);
$('.posts').scroll(function() {
if($("#loading").css('display') == 'none') {
if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
var limitStart = $("#results li").length;
loadResults(limitStart);
}
}
});function loadResults(limitStart) {
$("#loading").show();
$.ajax({
url: "posts.php",
type: "post",
dataType: "json",
data: {
limitStart: limitStart
},
success: function(data) {
$.each(data, function(key, value) {
$("#results").append("<li id='"+key.id+"'>"+value.title+"<img src='"+value.image+"' width='200px' height='200px'></li>");
});
$("#loading").hide();
}
});
};
});
</script>
|
posts.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<?php
require_once('db.php');
$limitStart = $_POST['limitStart'];
$limitCount = 10; // Set how much data you have to fetch on each request
if(isset($limitStart ) || !empty($limitStart)) {
$query = "SELECT id, title, image FROM post ORDER BY id limit $limitStart, $limitCount";
$result = mysqli_query($con, $query);
$res = array();
while($resultSet = mysqli_fetch_assoc($result)) {
$res[] = array('id'=>$resultSet['id'],'title'=>$resultSet['title'],'image'=>$resultSet['image']);
}
echo json_encode($res);
}
?>
|