Auto Loading Records With PHP Using Ajax

Auto loading record is very important functionality to update a page based on window scroll, in real scenario you can see more post loading on your Facebook wall, whenever you reach at the end of the page. The functionality is whenever the vertical scroll down the records will update more records. We will use jQuery to get records async manner. You can download the source code at the end of the tutorial.

autoload-records

Step 1: We will create a table that will contain all records and add some dummy records to the MySQL table.

<ol id="results">
</ol>
<div class="result_div" style="display:none" align="center"><img src="ajax-loader.gif"></div>

Step 2: We will call jquery into the index file head section of index.php file.

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

Step 3: We will create a connection file and call into the ajax PHP file and index file.

$db_username 	= 'root';
$db_password 	= '';
$db_name 		= 'test';
$db_host 		= 'localhost';
$limit = 5;
$mysqli = new mysqli($db_host, $db_username, $db_password,$db_name);

You need to change the connection object value as per your database credentials.

Step 4: We will call jquery ajax call into the index file and add an event for window scrolling.

$(window).scroll(function() { //detect page scroll
		
		if($(window).scrollTop() + $(window).height() == $(document).height())  //user scrolled to bottom of the page?
		{
			
			if(initRec <= total_rec &amp;&amp; loading==false) //there's more data to load
			{
				loading = true;
				$('.result_div').show(); //show loading image
				
				//load data from the server
				$.post('autoload.php',{'tot_limit': initRec}, function(data){
									
					$("#results").append(data); //append received data

					//hide loading image
					$('.result_div').hide(); //hide loading image
					
					initRec++; 
					loading = false; 
				
				}).fail(function(xhr, ajaxOptions, thrownError) { //any errors?
					
					alert(thrownError); //alert with HTTP error
					$('.result_div').hide(); //hide loading image
					loading = false;
				
				});
				
			}
		}
	});

You need call the jquery method into the index file for first-time records display.

Leave a Reply

Your email address will not be published. Required fields are marked *