Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

A Simple Tutorial on Creating Infinite Scroll Using PHP and jQuery

DZone's Guide to

A Simple Tutorial on Creating Infinite Scroll Using PHP and jQuery

Code samples to ensure pages have smooth infinite scroll, using PHP and jQuery.

· Web Dev Zone
Free Resource

Try RAD Studio for FREE!  It’s the fastest way to develop cross-platform Native Apps with flexible Cloud services and broad IoT connectivity. Start Your Trial Today!

Despite the remarkable coding performed by you (the PHP developer) for ensuring the smooth loading of web pages, there are scenarios wherein it takes way too long for the data to load on a web page. It is here that PHP and jQuery has a unique role to play. You can leverage them for displaying a massive amount of data on a web page, without affecting the page loading speed. All you need to do is simply implement the script using jQuery. Doing this would limit the initial loading of data until the user scrolls down and reaches the final limit. In today's tutorial, I'll be sharing with you the process of creating infinite scroll for a page that needs to include a lot of data/information.

Step 1: Create a Database Table

As the very first step, we need to have a database table that include all the data(the one which is to be displayed on the webpage) along with a unique id. For this, you can use Auto Increment feature(along with Primary key) as shown below:

Step 2: Use load_data.php

CREATE TABLE messages(

mes_id INT PRIMARY KEY AUTO_INCREMENT,

msg TEXT);


Load_data.php is being used for allowing jQuery to send the request that's responsible for fetching data that's older than the previous one. Have a look at the below sample of load data script:

<?php

include('config.php');

$lastmsg_id = $_GET ['lastmsg_id'];

$action = $_GET ['action'];

if($action <> "get")

{

?>

<script type = "text/javascript" src="jquery.js"> </script>

<script type = "text/javascript">

$(document).ready(function()

{

function lastmsg_function()

{

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()){

lastmsg_funtion();

}

});


});


</script>


</head>


<body>


<?php


include ( 'load_first.php' ); //inclusion of load_first.php


?>

<div id = "last_msg_loader"> </div>

</body>

</html>

<?php


}

else


{

include ( 'load_second.php' ); //inclusion of load_second.php


}

?>


As the user scrolls down the webpage, the ($(window).scroll) script would automatically determine that the user is at the bottom of the page. After this, the last_msg_function() would call load_data.php file in addition to adding the HTML data which would be returned after the last data. Moreover, in the above code snippet, you can also view the ($(window).scrollTop() == $(document).height() - $(window).height()) command which will be executed for determining the direction of scroll. Once the scroll direction is being identified, the expression within the statement would check whether the scrolled height is equal to window height. If it is, only then more data would be loaded on the web page.

Step 3: Use the load_first.php

Have a look at the below mentioned PHP code that loads 25 rows which have been fetched from message table(the one created earlier in this post):

<?php

$sql = mysql_query ( " SELECT * FROM messages ORDER BY mes_id DESC LIMIT 25 " );

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

}

?>


Step 4: Use load_second.php

Now, the load_second.php code is being used for loading 8 rows which are lesser than the last_msg_id that's been fetched from the message table. Have a look at the below PHP code for this step:

<?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 8" );

$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

}

?>


Step 5: Add the CSS elements

The addition of specific CSS elements will present the data in a refined format. In this tutorial, I've used the CSS elements that have rendered style elements to the post number and message box. Have a look at the below sample CSS file:

body

{

font-family: Georgia, ‘Times New Roman’, Times, serif;

font-size:20px;

}

.message_box

{

height:50px;

width:605px;

border:dashed 2px #48B1D9;

padding:6px ;

}

#last_msg_loader

{

text-align: right;

width: 915px;

margin: -120px auto 0 auto;

}

.number

{

float:right;

background-color:#48B1D9;

color:#000;

font-weight:bold;

}


What makes PHP and jQuery the best fits for loading huge chunks of data on a single web page?

One of the greatest advantages of using PHP and jQuery for loading data is that it allows dynamic loading of data, while the user chooses to scroll down the page. It is interesting to know that some of the most popular websites similar to Google+, Facebook and Twitter have employed this technique for loading data on web pages.

Get Your Apps to Customers 5X Faster with RAD Studio. Brought to you in partnership with Embarcadero.

Topics:
php ,jquery ,scrolling ,web dev

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}