Load More Pagination allows users to load additional records dynamically by clicking a button without refreshing the page. PHP fetches the next set of records from the database using AJAX.
A limited number of records are loaded initially. Each click sends an offset value to the server, which returns the next batch of records.
// HTML structure and AJAX logic
<div id="records"></div>
<button id="loadMore">Load More</button>
let offset = 0;
const limit = 5;
function loadMore() {
const xhr = new XMLHttpRequest();
xhr.open("GET","load_more.php?offset="+offset+"&limit="+limit,true);
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status==200){
if(xhr.responseText.trim()!==""){
document.getElementById("records").innerHTML+=xhr.responseText;
offset+=limit;
}else{
document.getElementById("loadMore").disabled=true;
document.getElementById("loadMore").innerText="No more records";
}
}
};
xhr.send();
}
window.onload=loadMore;
document.getElementById("loadMore").addEventListener("click",loadMore);
// PHP backend to fetch records
<?php
$conn=new mysqli("localhost","username","password","database");
$offset=(int)($_GET['offset']??0);
$limit=(int)($_GET['limit']??5);
$result=$conn->query("SELECT * FROM users LIMIT $offset,$limit");
while($row=$result->fetch_assoc()){
echo "<div>".$row['name']." - ".$row['email']."</div>";
}
$conn->close();
?>
Each click loads the next set of records and appends them below the previous ones until no more records exist.
This logic can be enhanced with infinite scrolling by triggering loadMore() on scroll events.