Over 05 years we help companies reach their financial and branding goals. webtechguru is a values-driven technology agency dedicated.

Gallery

Contacts

support@webtechguru.in

How to cretae a loadmore pagination in php with ajax

Load more pagination is a common feature in web development, allowing users to fetch and display additional content as they scroll or click a “Load More” button. In this tutorial, we’ll walk through the steps to implement a simple load more pagination using PHP and AJAX. The example will include a MySQL database to demonstrate fetching real data.

Prerequisites

– Basic knowledge of HTML, JavaScript, PHP, and MySQL.
– A web server environment (e.g., Apache, Nginx) with PHP and MySQL support.

Steps

1. Database Setup

– Create a MySQL database (e.g., named `test`).
– Create a table (e.g., named `employee`) with columns: (employee_id, first_name, last_name, email, phone, hire_date, salary)

-- Create the employee table
CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    email VARCHAR(100),
    phone VARCHAR(20),
    hire_date DATE,
    salary DECIMAL(10, 2)
);

-- Insert dummy data for 30 employees
INSERT INTO employees (employee_id, first_name, last_name, email, phone, hire_date, salary)
VALUES
    (1, 'John', 'Doe', 'john.doe@example.com', '123-456-7890', '2023-01-01', 50000.00),
    (2, 'Jane', 'Smith', 'jane.smith@example.com', '987-654-3210', '2023-02-01', 60000.00),
    (3, 'Robert', 'Johnson', 'robert.johnson@example.com', '555-123-4567', '2023-03-01', 55000.00),
    (4, 'Emily', 'Davis', 'emily.davis@example.com', '789-456-1230', '2023-04-01', 62000.00),
    (5, 'Michael', 'Miller', 'michael.miller@example.com', '321-654-0987', '2023-05-01', 58000.00),
    (6, 'Amanda', 'Brown', 'amanda.brown@example.com', '987-654-3210', '2023-06-01', 65000.00),
    (7, 'David', 'Wilson', 'david.wilson@example.com', '555-789-0123', '2023-07-01', 70000.00),
    (8, 'Sarah', 'Johnson', 'sarah.johnson@example.com', '123-456-7890', '2023-08-01', 53000.00),
    (9, 'Daniel', 'Clark', 'daniel.clark@example.com', '789-012-3456', '2023-09-01', 56000.00),
    (10, 'Olivia', 'Anderson', 'olivia.anderson@example.com', '555-123-4567', '2023-10-01', 59000.00),
    (11, 'James', 'Taylor', 'james.taylor@example.com', '321-987-6543', '2023-11-01', 51000.00),
    (12, 'Sophia', 'White', 'sophia.white@example.com', '555-555-5555', '2023-12-01', 54000.00),
    (13, 'Matthew', 'Harris', 'matthew.harris@example.com', '789-654-3210', '2024-01-01', 62000.00),
    (14, 'Emma', 'Moore', 'emma.moore@example.com', '555-987-6543', '2024-02-01', 58000.00),
    (15, 'Christopher', 'Evans', 'christopher.evans@example.com', '123-654-7890', '2024-03-01', 66000.00),
    (16, 'Ava', 'Thompson', 'ava.thompson@example.com', '987-654-3210', '2024-04-01', 71000.00),
    (17, 'Joseph', 'Martin', 'joseph.martin@example.com', '555-321-6540', '2024-05-01', 55000.00),
    (18, 'Mia', 'Anderson', 'mia.anderson@example.com', '321-555-7890', '2024-06-01', 59000.00),
    (19, 'William', 'Brown', 'william.brown@example.com', '555-789-0123', '2024-07-01', 64000.00),
    (20, 'Ella', 'Garcia', 'ella.garcia@example.com', '123-456-7890', '2024-08-01', 52000.00),
    (21, 'Benjamin', 'Davis', 'benjamin.davis@example.com', '789-012-3456', '2024-09-01', 57000.00),
    (22, 'Amelia', 'Martinez', 'amelia.martinez@example.com', '555-123-4567', '2024-10-01', 60000.00),
    (23, 'Elijah', 'Hernandez', 'elijah.hernandez@example.com', '321-987-6543', '2024-11-01', 63000.00),
    (24, 'Grace', 'Young', 'grace.young@example.com', '555-555-5555', '2024-12-01', 68000.00),
    (25, 'Daniel', 'Lee', 'daniel.lee@example.com', '789-654-3210', '2025-01-01', 54000.00),
    (26, 'Madison', 'Taylor', 'madison.taylor@example.com', '555-987-6543', '2025-02-01', 59000.00),
    (27, 'Jackson', 'Moore', 'jackson.moore@example.com', '123-654-7890', '2025-03-01', 64000.00),
    (28, 'Lily', 'Brown', 'lily.brown@example.com', '987-654-3210', '2025-04-01', 69000.00),
    (29, 'Logan', 'Harris', 'logan.harris@example.com', '555-321-6540', '2025-05-01', 57000.00),
    (30, 'Chloe', 'Anderson', 'chloe.anderson@example.com', '321-555-7890', '2025-06-01', 61000.00);

2. HTML (index.php)

– Create the HTML structure for displaying the employee data and the “Load More” button.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Load More Pagination with AJAX</title>
    <!-- Added bootstrap css file  -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
    <!-- Added bootstrap js cdn file  -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
    <!-- Added jquery cdn file -->
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>

    <!-- Start table -->

    <div class="container p-5">
        <h3 class="p-4 alert-primary font-weight-normal text-center">Load More Pagination with Php, Ajax, and Bootstrap</h3>
        <div class="table-responsive">
            <table class="table table-bordered">
                <thead class="alert-info">
                    <tr>
                        <th>Employee_Id</th>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Email</th>
                        <th>Hire Date</th>
                        <th>Salary</th>
                    </tr>
                </thead>
                <tbody id="employee-list">
                    
                </tbody>
            </table>

            <div class="d-flex justify-content-center align-items-center">
                <button id="load-more" class="btn btn-success shadow-none">Load More</button>
            </div>
        </div>
    </div>

    <!-- End table -->

    <script>
        $(document).ready(function () {
        let page = 1;

        // Function to load employees using AJAX
        function loadEmployees() {
            $.ajax({
                url: 'pagination-ajax.php',
                method: 'POST',
                data: { page: page },
                success: function (data) {
                    $('#employee-list').append(data);
                    page++; // Increment page for the next request

                    if(data === 'No more records'){
                        $('#load-more').hide();
                    }
                },
                error: function (error) {
                    console.log('Error:', error);
                }
            });
        }

        // Load initial set of employees
        loadEmployees();

        // Load more button click event
        $('#load-more').on('click', function () {
            loadEmployees();
        });
    });

    </script>
</body>
</html>

3. PHP (pagination-ajax.php)

– Create a PHP script to handle the server-side logic, connect to the database, and fetch employee data.

 

<?php
// Database connection parameters
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'test';

// Create a connection
$conn = new mysqli($host, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get the page parameter from the AJAX request
$page = $_POST['page'];

// Calculate limits for pagination
$employeesPerPage = 5;
$start = ($page - 1) * $employeesPerPage;

// Simulated database query. Replace this with your actual database query.
$sql = "SELECT * FROM employees LIMIT $start, $employeesPerPage";
$result = $conn->query($sql);

// Output employee data
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) { ?>

        <tr>
            <td><?php echo $row['employee_id']; ?></td>
            <td><?php echo $row['first_name']; ?></td>
            <td><?php echo $row['last_name']; ?></td>
            <td><?php echo $row['email']; ?></td>
            <td><?php echo $row['hire_date']; ?></td>
            <td><?php echo $row['salary']; ?></td>
        </tr>
       
     <?php }
} else {
    echo "No more records";
}

// Close the database connection
$conn->close();
?>

 

Conclusion

By following these steps, you can create a simple load more pagination system using PHP and AJAX. This example uses jQuery for simplicity, but you can adapt it to vanilla JavaScript if preferred. Customize the PHP script according to your database structure and connection details. This tutorial provides a foundation that you can build upon to implement more advanced features and enhancements based on your specific requirements.

Author

Admin

Leave a comment

Your email address will not be published. Required fields are marked *