In my home page, I'm showing the last three rows of my table via this code:
$result = mysql_query("SELECT id, title, date, text FROM news WHERE hshs=1 ORDER BY date DESC LIMIT $p") or die(mysql_error());
Where $p
comes from:
$p = $_GET['page'];
if ( empty($p) ) {
$p = 2;
$more = 4;
}
else{
if ( $p < $postnum ) {
$more = $p + 2;
}
else{
$finish = 1;
}
}
and $postnum
is number of the rows.
Then, I have this line to load more posts:
if ( $finish != 1 ) {
echo '<center><strong><a id="loadmore" href="?page='.$more.'">Load more posts...</a></strong></center>';
}
This does its job beautifully. But I have a problem. I don't want to load the whole page again to load more posts. Because this will show the page again from the top of it! I want the page to stay where it is without scrolling the user to the top of it, and then loads more posts.
Hope you will understand me! :)
Step 1) Call an Ajax request on click of "Load more posts..".
Step 2) PHP will return more posts as response to Ajax request.
Step 3) Append Ajax result in appropriate div (preferably using jQuery).
Note: Use limit in MySQL query for proper paging mechanism.
Use jQuery:
jQuery( document ).on( 'click', '#loadmore', function() {
jQuery.ajax({
url: "./path-to-your-sql-load",
data: {
ajax: '1',
page: '<?php echo $page+1; ?>'
},
method: 'get',
success: function( response ) {
console.log( response );
jQuery( '#results' ).append( response );
}
});
} );
And in your SQL load you can check if it is ajax like this:
if( $_GET[ 'ajax' ] == '1' ):
// ajax
else:
// no ajax
endif;