How can JavaScript be used to improve the user experience of PHP pagination scripts?

PHP pagination scripts often require the page to reload when navigating between pages, leading to a less seamless user experience. By incorporating JavaScript, we can implement AJAX pagination to load new content dynamically without refreshing the entire page, resulting in a smoother and more interactive browsing experience for users.

// PHP code snippet with AJAX pagination using JavaScript

// Include jQuery library
echo '<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>';

// Output pagination links with JavaScript AJAX functionality
echo '<div id="pagination">';
for ($i = 1; $i <= $total_pages; $i++) {
    echo '<a href="#" class="page-link" data-page="' . $i . '">' . $i . '</a>';
}
echo '</div>';

// JavaScript code to handle AJAX pagination
echo '<script>
$(document).ready(function() {
    $(".page-link").click(function(e) {
        e.preventDefault();
        var page = $(this).data("page");
        
        $.ajax({
            url: "pagination.php",
            type: "POST",
            data: { page: page },
            success: function(response) {
                $("#content").html(response);
            },
            error: function() {
                alert("Error loading page");
            }
        });
    });
});
</script>';