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 Create Pagination with AJAX in PHP

Pagination is a crucial feature for any website that displays a large amount of data, such as blog posts, product listings, or search results. Implementing pagination can significantly improve the user experience by breaking down content into manageable chunks. When you combine pagination with AJAX (Asynchronous JavaScript and XML) in PHP, you can create a more dynamic and user-friendly interface that loads new content without refreshing the entire page.

In this article, we will guide you through the process of creating a pagination system with AJAX in PHP. We will cover the following steps:

1. Set up your PHP environment.
2. Create a database and populate it with sample data.
3. Design the HTML structure.
4. Fetch and display initial data.
5. Implement AJAX for seamless pagination.

Step 1: Set up your PHP environment

Before we start, make sure you have a working PHP environment. You can use XAMPP, WAMP, or any other server setup to run PHP scripts.

Step 2: Create a database and populate it with sample data

For this tutorial, let’s assume you have a MySQL database named ‘pagination’ with a table named ‘student’. You can create this table with fields like ‘id’, ‘name’, ‘class’, ‘mark’ and ‘gender’, and populate it with sample data.

CREATE TABLE IF NOT EXISTS `student` (
  `id` int(2) NOT NULL DEFAULT '0',
  `name` varchar(50) CHARACTER SET utf8 NOT NULL DEFAULT '',
  `class` varchar(10) CHARACTER SET utf8 NOT NULL DEFAULT '',
  `mark` int(3) NOT NULL DEFAULT '0',
  `gender` varchar(6) CHARACTER SET utf8 NOT NULL DEFAULT 'male'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `student` (`id`, `name`, `class`, `mark`, `gender`) VALUES
(1, 'John Deo', 'Four', 75, 'female'),
(2, 'Max Ruin', 'Three', 85, 'male'),
(3, 'Arnold', 'Three', 55, 'male'),
(4, 'Krish Star', 'Four', 60, 'female'),
(5, 'John Mike', 'Four', 60, 'female'),
(6, 'Alex John', 'Four', 55, 'male'),
(7, 'My John Rob', 'Five', 78, 'male'),
(8, 'Asruid', 'Five', 85, 'male'),
(9, 'Tes Qry', 'Six', 78, 'male'),
(10, 'Big John', 'Four', 55, 'female'),
(11, 'Ronald', 'Six', 89, 'female'),
(12, 'Recky', 'Six', 94, 'female'),
(13, 'Kty', 'Seven', 88, 'female'),
(14, 'Bigy', 'Seven', 88, 'female'),
(15, 'Tade Row', 'Four', 88, 'male'),
(16, 'Gimmy', 'Four', 88, 'male'),
(17, 'Tumyu', 'Six', 54, 'male'),
(18, 'Honny', 'Five', 75, 'male'),
(19, 'Tinny', 'Nine', 18, 'male'),
(20, 'Jackly', 'Nine', 65, 'female'),
(21, 'Babby John', 'Four', 69, 'female'),
(22, 'Reggid', 'Seven', 55, 'female'),
(23, 'Herod', 'Eight', 79, 'male'),
(24, 'Tiddy Now', 'Seven', 78, 'male'),
(25, 'Giff Tow', 'Seven', 88, 'male'),
(26, 'Crelea', 'Seven', 79, 'male'),
(27, 'Big Nose', 'Three', 81, 'female'),
(28, 'Rojj Base', 'Seven', 86, 'female'),
(29, 'Tess Played', 'Seven', 55, 'male'),
(30, 'Reppy Red', 'Six', 79, 'female'),
(31, 'Marry Toeey', 'Four', 88, 'male'),
(32, 'Binn Rott', 'Seven', 90, 'female'),
(33, 'Kenn Rein', 'Six', 96, 'female'),
(34, 'Gain Toe', 'Seven', 69, 'male'),
(35, 'Rows Noump', 'Six', 88, 'female');

Step 3: Design the HTML structure

Create an HTML structure for your pagination. You can use a simple HTML layout with a div element to display the content and another div to hold the pagination links. Here’s a basic example:

index.php

<?php 

include('database.php');

$limit = 5;
$sql = "SELECT COUNT(id) FROM student";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_row($result);
$total_records = $row[0];

 ?>


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <!-- Added the custom css file -->
    <link rel="stylesheet" href="">
    <!-- Added jquery cdn -->
    <script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
    <!-- Added bootstrap css file -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <!-- Added bootstrap js file -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</head>
<body>
    <input type="hidden" id="total-records" value="">

    <div class="container  p-5">
    <h3>Pagination with ajax</h3><hr>


    <div class="table-responsive" id="pagi-tbl-div" value="total_records"></div>

    <!--  Pagination 2  -->
    <nav aria-label="Page navigation example">
      <ul class="pagination" id="pagination">
      </ul>
    </nav>


    </div>


 <!-- Start script code here -->
<script>
    jQuery(document).ready(function(){


        function fetchTblData(page){

            jQuery.ajax({
                url:'pagination_ajax.php',
                type:'post',
                data:{page:page},
                success:function(response){
                  jQuery('#pagi-tbl-div').html(response);
                }
            })
        }

        fetchTblData(1);



    // Pagination 

     var limit = '<?php echo $limit ?>';
     var total_records = <?php echo $total_records ?>;
     var total_pages = Math.ceil(total_records / limit);
     //alert(total_pages);


    if(total_pages){
        for(i=1; i<=total_pages; i++){

           // Condition for fisrt page
            if(i==1){
            jQuery('#pagination').append('<li class="page-item active" data-id="'+i+'"><a class="page-link" href="JavaScript:Void(0);" data-id="'+i+'" >'+i+'</a></li>');
            }else{
            jQuery('#pagination').append('<li class="page-item" data-id="'+i+'"><a class="page-link" href="JavaScript:Void(0);" data-id="'+i+'" >'+i+'</a></li>');
            }
           
        }
    }
      
        jQuery('.page-item').click(function(event){
            event.preventDefault();
            var btn_id = jQuery(this).data('id');
            jQuery('.page-item').removeClass('active');
            jQuery(this).addClass('active');
           fetchTblData(btn_id);
        });

    })
</script>

    
</body>
</html>

Step 4: Fetch and display initial data

In your PHP file, you should retrieve the initial data from the database and display it. You can use PHP to connect to the database, run a query, and echo the results in the ‘content’ div.

database.php

<?php 

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pagination";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}


 ?>

pagination_ajax.php

<?php

include('database.php');

$limit = 5;  
if (isset($_POST["page"])){ $page  = $_POST["page"]; } else { $page=1; };  
$start_from = ($page-1) * $limit;  
  
$sql = "SELECT * FROM student ORDER BY id ASC LIMIT $start_from, $limit";  

$result = $conn->query($sql);

?>

<table class="table table-bordered">
     <thead class="bg-light ">
       <tr>
         <td>ID</td>
         <td>Name</td>
         <td>Class</td>
         <td>Mark</td>
         <td>Gender</td>
       </tr>
     </thead>
     <tbody>

<?php 

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
   ?>
        <tr>
          <td><?php echo $row['id'] ?></td>
          <td><?php echo $row['name'] ?></td>
          <td><?php echo $row['class'] ?></td>
          <td><?php echo $row['mark'] ?></td>
          <td><?php echo $row['gender'] ?></td>
        </tr>

 <?php } ?>

    </tbody>
   </table>

 <?php
} else {
  echo "0 results";
}
$conn->close();


?>

Step 5: Implement AJAX for seamless pagination

Now, let’s make the pagination dynamic with AJAX. When a user clicks on a page number, we will use AJAX to load the corresponding data and update the ‘content’ div without a full page reload. Here’s a basic AJAX script to get you started

Make sure you create the ‘pagination_ajax.php’ file to handle AJAX requests. In this file, you should query the database and return the appropriate data for the requested page.

With this setup, your pagination system is ready to go. Users can navigate through the data seamlessly without experiencing full-page reloads. You can enhance the design and functionality according to your project’s requirements.

Creating a pagination system with AJAX in PHP can greatly improve your website’s user experience by making it more interactive and responsive. This tutorial covered the fundamental steps, but you can expand upon this foundation to create more sophisticated pagination features for your specific needs.

Author

Admin

Leave a comment

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