AJAX Pagination with PHP, MySQL, and Fetch
AJAX pagination loads another page of results without a full document navigation. The server should validate the requested page, apply a bounded page size, and return both records and pagination information.
Validate page parameters
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
$page = max(1, (int)($page ?: 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;
$stmt = $pdo->prepare('SELECT id, title FROM posts ORDER BY id DESC LIMIT :limit OFFSET :offset');
$stmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
Use a maximum page size and consider a stable indexed sort key. For large datasets, cursor-based pagination may perform better than very large offsets.
Return a predictable response
A JSON response can include items, page, perPage, and hasMore. The browser can append or replace result elements using DOM APIs and text-safe rendering.
Handle edge cases
Account for empty pages, deleted records, changing datasets, and repeated clicks. Disable the load-more control while a request is pending and provide an accessible loading or end-of-results message.