This article will show you to how load contents or data dynamically on window scroll like Twitter, Facebook, g+ and much more. Many websites which has more length contents to show users will use this module to avoid page loading time and display the contents dynamically to users without taking too much loading time. We can see it in Twitter, Facebook, Google Images etc., when we scroll down the page the rest of contents will be loaded automatically. Its is using for avoid the loading time and reduce the server pulling time.

window-on-scroll-load-data-php-mysql-jquery-by-asif18

This simple steps will pull data from the server easily.

Create database connection file called 'library.php':

<?php
mysql_connect("localhost", "root", "root") or die ("Oops! Server not connected"); // Connect to the host
mysql_select_db("demo") or die ("Oops! DB not connected"); // select the database
?>

Create and design view file called 'index.php':

<script type="text/javascript" src="jquery-1.9.1.js"></script>
<style>
.as_wrapper{
    margin:0 auto;
    width:500px;
    font-family:Arial;
    color:#333;
    font-size:14px;
}
.as_country_container{
    padding:20px;
    border:2px dashed #17A3F7;
    margin-bottom:10px;
}
</style>

Add this jQuery function for load the contents on window scroll function:

<script type="text/javascript">
$(document).ready(function(){  
    $(window).scroll(function(){ /* window on scroll run the function using jquery and ajax */
        var WindowHeight = $(window).height(); /* get the window height */
        if($(window).scrollTop() +1 >= $(document).height() - WindowHeight){ /* check is that user scrolls down to the bottom of the page */
            $("#loader").html("<img src='loading_icon.gif' alt='loading'/>"); /* displa the loading content */
            var LastDiv = $(".as_country_container:last"); /* get the last div of the dynamic content using ":last" */
            var LastId  = $(".as_country_container:last").attr("id"); /* get the id of the last div */
            var ValueToPass = "lastid="+LastId; /* create a variable that containing the url parameters which want to post to getdata.php file */
            $.ajax({ /* post the values using AJAX */
            type: "POST",
            url: "getdata.php",
            data: ValueToPass,
            cache: false,
                success: function(html){
                    $("#loader").html("");
                    if(html){
                        LastDiv.after(html); /* get the out put of the getdata.php file and append it after the last div using after(), for each scroll this function will execute and display the results */
                    }
                }
            });
            return false;
        }
        return false;
    });
});
</script>

After the <head> section display the contents dynamically from DB with a limit:

<div class="as_wrapper">
    <h1>Window on scroll load contents in php mysql jquery using simple jQuery bootstrap module</h1>
    <?php
    $country_select = mysql_query("SELECT * FROM `countries` ORDER BY country_id DESC LIMIT 10");
    while($fetch = mysql_fetch_array($country_select)){
    ?>
    <div class="as_country_container" id="<?php echo $fetch["country_id"]; ?>"> <!-- set the mysql row id or primary key value as div id here -->
        <table>
        <tr>
            <td style="width:300px;"><?php echo $fetch["country_name"]; ?></td>
            <td><img src="country_flags/<?php echo $fetch["country_code"]; ?>.png" alt="<?php echo $fetch["country_code"]; ?>" title="<?php echo $fetch["country_code"]; ?>" /></td>
        </tr>
        </table>
    </div>
    <?php
    }
    ?>
    <div id="loader"></div>
    <!-- here the rest of contents will display dynamically, after the 'as_country_container' class -->
</div>

Finally the index file will be like this:

<?php
/**
Simple bootstrap using php mysql jquery by asif18.com, for more tutorials visit : http://www.asif18.com
for this tutorial visit : http://www.asif18.com/4/php/window-on-scroll-load-contents-in-php-mysql-using-jquery-bootstrap/
**/
include 'library.php'; // include the database and server connection file
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple jQuery PHP MySql bootsrap module by Asif18</title>
<meta name="keywords" content="boostrap in jquey, on scroll load data in php mysql, simple jQuery bootstrap"/>
<meta name="description" content="window on scroll load contents using php, mysql, jquery a simple bootsrap module in jQuery"/>
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<style>
.as_wrapper{
    margin:0 auto;
    width:500px;
    font-family:Arial;
    color:#333;
    font-size:14px;
}
.as_country_container{
    padding:20px;
    border:2px dashed #17A3F7;
    margin-bottom:10px;
}
</style>
<script type="text/javascript">
$(document).ready(function(){  
    $(window).scroll(function(){ /* window on scroll run the function using jquery and ajax */
        var WindowHeight = $(window).height(); /* get the window height */
        if($(window).scrollTop() +1 >= $(document).height() - WindowHeight){ /* check is that user scrolls down to the bottom of the page */
            $("#loader").html("<img src='loading_icon.gif' alt='loading'/>"); /* displa the loading content */
            var LastDiv = $(".as_country_container:last"); /* get the last div of the dynamic content using ":last" */
            var LastId  = $(".as_country_container:last").attr("id"); /* get the id of the last div */
            var ValueToPass = "lastid="+LastId; /* create a variable that containing the url parameters which want to post to getdata.php file */
            $.ajax({ /* post the values using AJAX */
            type: "POST",
            url: "getdata.php",
            data: ValueToPass,
            cache: false,
                success: function(html){
                    $("#loader").html("");
                    if(html){
                        LastDiv.after(html); /* get the out put of the getdata.php file and append it after the last div using after(), for each scroll this function will execute and display the results */
                    }
                }
            });
            return false;
        }
        return false;
    });
});
</script>
</head>
 
<body>
<div class="as_wrapper">
    <h1>Window on scroll load contents in php mysql jquery using simple jQuery bootstrap module</h1>
    <?php
    $country_select = mysql_query("SELECT * FROM `countries` ORDER BY country_id DESC LIMIT 10");
    while($fetch = mysql_fetch_array($country_select)){
    ?>
    <div class="as_country_container" id="<?php echo $fetch["country_id"]; ?>"> <!-- set the mysql row id or primary key value as div id here -->
        <table>
        <tr>
            <td style="width:300px;"><?php echo $fetch["country_name"]; ?></td>
            <td><img src="country_flags/<?php echo $fetch["country_code"]; ?>.png" alt="<?php echo $fetch["country_code"]; ?>" title="<?php echo $fetch["country_code"]; ?>" /></td>
        </tr>
        </table>
    </div>
    <?php
    }
    ?>
    <div id="loader"></div>
    <!-- here the rest of contents will display dynamically, after the 'as_country_container' class -->
</div>
</body>
</html>

Finally create 'getdata.php' file to POST and get the rest of the contents from DB:

<?php
include 'library.php'; // include the library file
session_start();
if(isset($_POST["lastid"]) && $_POST["lastid"] != "0"){
	$lastid = $_POST["lastid"]; // save the posted value in a variable
	if($_SESSION['lastid'] != $_POST["lastid"]) { // Check session for avoid duplicate records
		$country_select = mysql_query("SELECT * FROM `countries` WHERE country_id < '$lastid' ORDER BY country_id DESC LIMIT 5");
		if(mysql_num_rows($country_select) > 0){
			$last_id = '';
			while($fetch = mysql_fetch_array($country_select)){
			?>
			<div class="as_country_container" id="<?php echo $fetch["country_id"]; ?>">
				<table>
				<tr>
					<td style="width:300px;"><?php echo $fetch["country_name"]; ?></td>
					<td><img src="country_flags/<?php echo $fetch["country_code"]; ?>.png" alt="<?php echo $fetch["country_code"]; ?>" title="<?php echo $fetch["country_code"]; ?>" /></td>
				</tr>
				</table>
			</div>
		<?php
			$last_id = $fetch["country_id"];
			}
			$_SESSION['lastid'] = $lastid; // Create session for check and avoid dupilicate records
		}
	}
}
?>

When the page runs, the jquery will get the last div's ID which was the mysql row's id and post it to the getdata.php file each time when user scrolls to the bottom of the page. In get data.php file just run the mysql query less that '<' the posted value.

NOTE : each mysql query must contain the ORDER BY ASC or DESC for continuous looping and correct resulting

24 Comments


anonymous
anonymous said..
Thanks so much.
anonymous
anonymous said..
ramlaxman
ramlaxman said..
a n
a n said..
Its repeating somew contents again n agian
anonymous
anonymous said..
wow.. thanks yar.. its really worthy for me... thanks alot for posting
Muhammad
Muhammad said..
Thanks bro but there is a little problem in the script it loads the data even when we not scroll at the bottom of page e.g if we scroll up/down it load all the data Regards
Ashraf ali
Ashraf ali said..
hi i like your work ,but i have a question for you,i am using this in <ul><li>. where <li>work in a while and i am trying to get the data in <li> everything works fine but after getting the lastid it repeats the loading. please tell me the issue
Asif
Asif said..
@Ashraf You can fix this issues using mysql_num_rows() in ur php file, if(mysql_num_rows() > 0){ echo "your <li> stuff </li>"; } by this while loop will not generate <li>'s
sivaraj
sivaraj said..
its repeating some contents again and agian .plz help me
Asif
Asif said..
@sivaraj, Use mysql_num_rows before the while("loop") it will solve your duplicate issue. :)
Kavi
Kavi said..
hey pal, I'm having the same problem. I did mysql_num_rows before the while.but still previous divs repeating. help me bro..
Asif
Asif said..
@Kavi, @sivaraj, i have altered some codes above please make a note on it and download the latest file now from the above 'Download' link. Let me know if any quires.
anonymous
anonymous said..
Miraz Hossain
Miraz Hossain said..
Hi, As others said, its repeating the same data again and again, i have downloaded the source codes and ran them in my localhost, but i have found that the problem persists in your own vary source code.
anonymous
anonymous said..
anonymous
anonymous said..
thanks... Majid
Rakesh Chand
Rakesh Chand said..
Sk Azhar Islam
Sk Azhar Islam said..
Hi Asif I m new on php.its good thanx. its shown on full window.can i fix it with in 300px div.
shweta
shweta said..
I resolved the repeating contents issue by using following condition if($(window).scrollTop() + window.innerHeight == $(document).height()) instead of if($(window).scrollTop() +1 >= $(document).height() - WindowHeight) in windows.scroll
Asif
Asif said..
@shweta, thank your update. Really appreciable. I have done some changes in the getdata.php file to avoid the data repeating. Now we have two solutions to solve this issue. (Y)
Asif
Asif said..
@Sk Azhar Islam, you can do it by creating a parent div with 300px height for that
anonymous
anonymous said..
its repeating some contents again and agian .plz help me
anonymous
anonymous said..
repeating problem is solved: .as_container { padding: 20px; height:150px; margin-bottom: 10px; } and if($(window).scrollTop() + window.innerHeight == $(document).height()) { is change javascript. After work is fine.
Bhavesh vyas
Bhavesh vyas said..
There is a error on this module demo will not work propertly

Post a comment



Mohamed Asif Am a web developer i love web designing, web developing. for any tutorials mail me at asif18[at]asif18.com