Asif18

Author:
{ Comments }

This article will show you to how load more contents or data dynamically on window scroll down like Twitter, Facebook, G+ and Dzone and much more. Many websites which has more data to show to users will use this module to avoid page loading time and display the contents dynamically to users without taking too much loading time. When user scroll down the page the more data will be loaded automatically from the server using Ajax, PHP and MySql. It is using to 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

Comments (12)