← Back to Chapters

PHP AJAX Load More Pagination

? PHP AJAX Load More Pagination

? Quick Overview

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.

? Key Concepts

  • AJAX requests using JavaScript
  • Offset and limit based pagination
  • Dynamic DOM updates

? Syntax & Theory

A limited number of records are loaded initially. Each click sends an offset value to the server, which returns the next batch of records.

? Code Examples

? View Code Example
// 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);
? View Code Example
// 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();
?>

? Live Output / Explanation

Each click loads the next set of records and appends them below the previous ones until no more records exist.

? Interactive Example

This logic can be enhanced with infinite scrolling by triggering loadMore() on scroll events.

? Use Cases

  • Social media feeds
  • Product listings
  • Blog post archives

✅ Tips & Best Practices

  • Always sanitize offset and limit values
  • Use loading indicators for better UX
  • Prefer fetch() for modern apps

? Try It Yourself

  • Add a loading spinner
  • Implement infinite scrolling
  • Show user profile images