How to create Pagination using PHP, jQuery, and Ajax Source Code

List-Pagination-using-PHP-jQuery-and-Ajax-Tutorial

In this post you will learn about How to create Pagination using PHP, jQuery, and Ajax Source Code. Read this below article carefully and understand this to put impact in real life.

You will learn how to add a Pagination Feature to your HTML List loaded from a database in this tutorial. With the help of the jQuery library and Ajax Request, you can implement the mentioned functionality in your project. This function is particularly useful for reducing the time it takes for your website to load a page containing bulk list data.

Bulk data might slow down the loading of your website’s page. Because the data isn’t so vast yet, you won’t notice the delayed loading of the site page at first when the project is still new. However, by utilizing the Pagination Feature, you will be able to avoid delayed page loading in the future.

The First Steps

Install any local web server, such as XAMPP/WAMP, so that you can execute the simple web application we’ll be creating on your end.

Open the software’s Control Panel and start the Apache and MySQL servers if you’re using XAMPP/WAMPP.

Download Bootstrap v5 and the jQuery Library as well. After that, compile the libraries and save them in a directory where you’ll keep your source code.

Note: If you’re using XAMPP, make sure your source code folder is in the htdocs directory, however if you’re using WAMP, it should be in the www directory.

Constructing a Dummy Database

Open a new tab in your browser and go to https://localhost/phpmyadmin to access PHPmyAdmin. Make a new database with the name dummy_db.

Making Your Own Style Sheet

A small CSS (Cascading Style Sheet) script for customising the look of specific parts of the programme is provided below. Make a copy of this file and save it as custom.css.

:root {
    --bs-success-rgb: 71, 222, 152 !important;
}
 
html,
body {
    height: 100%;
    width: 100%;
    font-family: Apple Chancery, cursive;
}
 
.btn-info.text-light:hover,
.btn-info.text-light:focus {
    background: #000;
}
 
#pgn-container {
    position: relative;
}
 
#pgn-loader {
    position: absolute;
    height: calc(100%);
    width: calc(100%);
    background-color: rgba(17, 17, 17, 0.432);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 2;
}
 
.list-group[data-placeholder="true"]:empty:after {
    content: "No Data to Display";
    align-self: center;
    font-style: italic;
    font-size: .8em;
    color: rgb(66, 66, 66);
}

Designing the User Interface

The elements of our UI are coded in the script below. The navigation bar, List Element, Pagination Buttons, and other features are all included. This file should be saved as index.php.

<?php require_once('db-connect.php') ?>
	<!DOCTYPE html>
	<html lang="en">
	<head>
	    <meta charset="UTF-8">
	    <meta http-equiv="X-UA-Compatible" content="IE=edge">
	    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	    <title>Paginatation</title>
	    <link rel="stylesheet" href="./Font-Awesome-master/css/all.min.css">
	    <link rel="stylesheet" href="./css/bootstrap.min.css">
	    <link rel="stylesheet" href="./css/custom.css">
	    <script src="./js/jquery-3.6.0.min.js"></script>
	    <script src="./js/bootstrap.min.js"></script>
	    <script src="./js/script.js"></script>
	</head>
 
	<body class="bg-light">
	    <nav class="navbar navbar-expand-lg navbar-dark bg-dark bg-gradient" id="topNavBar">
	        <div class="container">
	            <a class="navbar-brand" href="https://sourcecodester.com">
	            Sourcecodester
	            </a>
 
	            <div>
	                <b class="text-light">Pagination using jQuery and Ajax</b>
	            </div>
	        </div>
	    </nav>
	    <div class="container py-5" id="page-container">
	        <!-- Table Container -->
	        <div id="pgn-container">
	            <div class="text-center" id="pgn-loader">
	                <div class="spinner-border text-primary" role="status">
	                    <span class="visually-hidden">Loading...</span>
	                </div>
	            </div>
	            <div class="row">
	                <div class="col-sm-12 col-md-6">
	                    <span><b>Total Records:</b> <span class='total-records'>0</span></span>
	                </div>
	                <div class="col-sm-12 col-md-6 text-end">
	                    <span><b>Showing</b> <span class='show-filter'></span></span>
	                </div>
	            </div>
	            <!-- List Field -->
	            <ul class="list-group" data-placeholder="true"></ul>
	            <!-- End of List Field -->
	            <div class="col-md-12 my-2">
	                <div class="row">
	                    <div class="justify-content-center">
	                        <div class="btn-group me-2" role="group" aria-label="First group">
	                            <button type="button" id="prev-page" class="btn btn-outline-secondary"><i class="fa fa-caret-left"></i></button>
 
	                            <button type="button" id="next-page" class="btn btn-outline-secondary"><i class="fa fa-caret-right"></i></button>
	                        </div>
	                    </div>
	                </div>
	            </div>
	        </div>
	        <!-- End of Table Container -->
	    </div>
	    <!-- List Item Clone Element  -->
	    <noscript id="list-item-clone">
	        <li class="list-group-item list-group-item-action pgn-item">
	            <h3 class="fw-bold item-title"></h3>
	            <hr>
	            <p class="item-description"></p>
	        </li>
	    </noscript>
	    <!-- End of List Item Clone Element  -->
 
	    <!-- Page Button Clone -->
	    <noscript id="ipage-clone">
	        <button type="button" class="btn btn-outline-secondary ipage-btns"></button>
	    </noscript>
	    <!-- End of Page Button Clone -->
 
	</body>
	<?php if(isset($conn)) $conn->close(); ?>
	</html>

Developing a PHP API

The PHP code below downloads the database records, counts the filtered and total records in the database, and counts the number of page buttons. This file should be saved as get_data.php.

<?php 
require_once('db-connect.php');
// array to send back
$resp = [];
// Limit data to display
$limit = 5;
if($_SERVER['REQUEST_METHOD'] =='POST'){
    $page = $_POST['page'];
    // Total Records
    $all_posts = $conn->query("SELECT * FROM `posts`");
    $total_data = number_format($all_posts->num_rows);
    $resp['total'] = $total_data;
 
    // total page count
    $resp['page_count'] = ceil($total_data / $limit);
 
    $offset = $page > 0 ? $page * $limit : 0;
 
    // Filtered Data
    $posts = $conn->query("SELECT * FROM `posts` order by `id` limit $limit offset $offset");
    $resp['total_filtered'] = number_format($posts->num_rows);
    $resp['filtered'] = number_format($offset + 1)." - ". number_format($offset + $posts->num_rows);
    while($row = $posts->fetch_assoc()){
        $row['title'] = $row['id'] . " - ".$row['title'];
        $row['description'] = str_replace("\n","<br/>",$row['description']);
        $resp['data'][] = $row;
    }
}
echo json_encode($resp);
$conn->close();
?>

How to Make a JavaScript File

The script below contains all of the JavaScript methods for loading, redirecting, and displaying data. This file should be saved as script.js.

// current page loaded
var current_page = 0;
// Vount of records
var _total = 0
window.pgn_loader_start = function() {
    $('#pgn-loader').removeClass('d-none')
}
window.pgn_loader_end = function() {
    $('#pgn-loader').addClass('d-none')
}
window.load_page_bts = function($count = 1) {
    $('#pgn-container .ipage-btns').remove()
    for (var i = 0; i < $count; i++) {
        var btn = $($('noscript#ipage-clone').html()).clone()
        btn.attr('data-page', i)
        btn.text(parseFloat(i + 1).toLocaleString())
        $('#pgn-container #next-page').before(btn)
        btn.click(function() {
            load_page($(this).attr('data-page'))
        })
    }
    $('#pgn-container .ipage-btns[data-page="' + current_page + '"]').addClass('active')
    if (current_page == 0) {
        $('#prev-page').attr('disabled', true)
    } else {
        $('#prev-page').attr('disabled', false)
    }
    if (current_page == (_total - 1)) {
        $('#next-page').attr('disabled', true)
    } else {
        $('#next-page').attr('disabled', false)
    }
}
window.load_page = function($page = 0) {
    current_page = $page
    pgn_loader_start();
    $.ajax({
        url: './get_data.php',
        method: 'POST',
        data: { page: $page },
        dataType: 'json',
        error: err => {
            console.error(err)
            alert("An error occurred while fetching data.")
            pgn_loader_end();
        },
        success: function(resp) {
            if (resp) {
                $('#pgn-container ul').html('')
                var data = resp.data || {};
                $('#pgn-container .total-records').text(resp.total)
                $('#pgn-container .show-filter').text(resp.filtered)
 
                // Load Pagination Buttons
                load_page_bts(resp.page_count)
                _total = resp.page_count
 
                Object.keys(data).map(k => {
                    var li = $($('noscript#list-item-clone').html()).clone()
                    li.find('.item-title').text(data[k].title)
                    li.find('.item-description').text(data[k].description)
                    $('#pgn-container ul').append(li)
                })
            } else {
                console.error(resp)
                alert("An error occurred while fetching data.")
            }
            setTimeout(() => {
                pgn_loader_end();
 
            }, 800)
        }
    })
}
 
$(function() {
    load_page()
    $('#prev-page').click(function() {
        load_page(current_page - 1)
    })
    $('#next-page').click(function() {
        load_page(current_page + 1)
    })
})

Done!

Final Words

In this post you learnt about How to create Pagination using PHP, jQuery, and Ajax Source Code. If you like this article please share with your friends and family to support our website. We wrote this article by researching on internet to find best content for you. You can find more articles like this on our website for free. We provided you some important tips regarding this topic by following them you can easily understand. If you need more information regarding How to create Pagination using PHP, jQuery, and Ajax Source Code you can ask in comments or you can contact us via contact us form available on this website. Thanks for reading and sharing.


One Comment on “How to create Pagination using PHP, jQuery, and Ajax Source Code”

  1. I was very happy to discover this website. I want to to thank you for your time due to this fantastic read!! I definitely liked every little bit of it and i also have you book marked to check out new things on your blog.

Leave a Reply

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