X
    Categories: JqueryMysqlPHP

Load Data while Scrolling Page Down with jQuery and PHP

This tutorial about my favorite placeDzone like data loading while page scrolling down with jQuery and PHP. We have lots of data but can not display all. This script helps you to display little data and make faster your website.

Database Table

CREATE TABLE messages(
mes_id INT PRIMARY KEY AUTO_INCREMENT,
msg TEXT);

load_data.php

When we are scrolling down a webpage, the script($(window).scroll) finds that you are at the bottom and calls the last_msg_funtion(). Take a look at $.post(“”) eg: $.post(“load_data.php?action=get&last_msg_id=35”)

<?php
include('config.php');
$last_msg_id=$_GET['last_msg_id'];
$action=$_GET['action'];

if($action <> "get")
{
?>

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
function last_msg_funtion() 
{ 
var ID=$(".message_box:last").attr("id");
$('div#last_msg_loader').html('<img src="bigLoader.gif">');
$.post("load_data.php?action=get&last_msg_id="+ID,

function(data){
if (data != "") {
$(".message_box:last").after(data); 
}
$('div#last_msg_loader').empty();
});
}; 

$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
last_msg_funtion();
}
}); 
});
</script>
</head>
<body>
<?php 
include('load_first.php'); //Include load_first.php 
?>
<div id="last_msg_loader"></div>
</body>
</html>
<?php
}

else
{
include('load_second.php'); //include load_second.php
}
?>

load_first.php


Contains PHP code to load 20 rows form the message table.

<?php
$sql=mysql_query("SELECT * FROM messages ORDER BY mes_id DESC LIMIT 20");
while($row=mysql_fetch_array($sql))
{
$msgID= $row['mes_id'];
$msg= $row['msg'];
?>
<div id="<?php echo $msgID; ?>" class="message_box" > 
<?php echo $msg; ?>
</div> 
<?php
} 
?>

load_second.php
Contains PHP code to load 5 rows less than last_msg_id form the message table.

<?php
$last_msg_id=$_GET['last_msg_id'];
$sql=mysql_query("SELECT * FROM messages WHERE mes_id < '$last_msg_id' ORDER BY mes_id DESC LIMIT 5");
$last_msg_id="";
while($row=mysql_fetch_array($sql))
{
$msgID= $row['mes_id'];
$msg= $row['msg']; 
?>
<div id="<?php echo $msgID; ?>" class="message_box" > 
<?php echo $msg; 
?>
</div>
<?php
} 
?>

CSS

body
{
font-family:'Georgia',Times New Roman, Times, serif;
font-size:18px;
}
.message_box
{
height:60px;
width:600px; 
border:dashed 1px #48B1D9; 
padding:5px ;
}
#last_msg_loader
{
text-align: right;
width: 920px;
margin: -125px auto 0 auto;
}
.number
{
float:right; 
background-color:#48B1D9; 
color:#000; 
font-weight:bold;
}

 

Marimuthu: