HOW TO PAGINATION WITH JQUERY AJAX PHP

HOW TO PAGINATION WITH JQUERY AJAX PHP

HOW TO PAGINATION WITH JQUERY AJAX PHP

0 Sales

Free

Pagination is very useful in the data list where the database lists a large number of records. Through diving records in multiple pages, it helps to load the complex data more quickly. Using PHP, the pagination feature can be easily integrated. Generally speaking, PHP Pagination loads data by browsing page reload links. If you want to improve the UI of the website and make the data list user-friendly, Ajax Pagination is the best choice.

 

Ajax Pagination helps create links to pagination and load data without refreshing the page. Using Ajax and PHP, you can add pagination to the list of data without reloading the page. In this guide, we'll teach you how to use jQuery, Ajax, PHP, and MySQL to incorporate pagination on the web page.

 

We will compile dynamic posts from the MySQL repository in the example script and list them with the links to the pagination. Using jQuery and Ajax, a limited number of records will be retrieved from the database through these pagination links without page reload. Ajax will be used on a single page without reloading a page to implement pagination functionality.

 

Before getting started to build Ajax Pagination in PHP, take a look at the files structure.

ajax_pagination_with_php/

├── dbConfig.php

├── index.php

├── getData.php

├── Pagination.class.php

├── js/

│   └── jquery.min.js

└── css/

    └── style.css


 

Pagination Library

 

Use PHP to add Ajax pagination to the data list with our custom pagination library. It creates links to check the data list paging. To configure the pagination and navigation links, numerous configuration options are available. Below are some widely used choices for configuration.

 

  • BaseURL–URL where the Ajax request is sent to collect the database records based on the pagination link.

  • TotalRows –Total record number.

  • PerPage–The number of records on each page.

  • ContentDiv–HTML component ID that will display the Ajax response information.

 

The example below illustrates how to use the category of Pagination.

 

// Include pagination library file

include_once 'Pagination.class.php';


// Initialize pagination class

$pagConfig = array(

    'baseURL' => 'getData.php',

    'totalRows' => $rowCount,

    'perPage' => 10,

    'contentDiv' => 'dataContainer'

);

$pagination =  new Pagination($pagConfig);


<!-- Display pagination links -->
<?php echo $pagination->createLinks(); ?>


 

Create Database Table

To store the dynamic data in the database, a table is required. The following SQL creates a table of posts in the MySQL database with some basic fields.

 

CREATE TABLE `posts` (

 `id` int(11) NOT NULL AUTO_INCREMENT,

 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,

 `created` datetime NOT NULL,

 `modified` datetime NOT NULL,

 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',

 PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


 

Database Configuration (dbConfig.php)

To link and pick the server, the dbConfig.php file is used. Specify the database host ($dbHost), username ($dbUsername), password ($dbPassword) and name ($dbName) according to your credentials for the MySQL database server.

 

<?php

// Database configuration

$dbHost     = "localhost";

$dbUsername = "root";

$dbPassword = "root";

$dbName     = "codexworld";


// Create database connection

$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);


// Check connection

if ($db->connect_error) {

    die("Connection failed: " . $db->connect_error);

}


 

Data List with Ajax Pagination (index.php)

jQuery Library:

 

Include the library jQuery, it is necessary for the pagination of Ajax.

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>


 

Loading Image:

 

The following jQuery code is used when starting / completing ajax query to show / hide overlay loading.

 

 

<script>

// Show loading overlay when ajax request starts

$( document ).ajaxStart(function() {

    $('.loading-overlay').show();

});


// Hide loading overlay when ajax request completes

$( document ).ajaxStop(function() {

    $('.loading-overlay').hide();

});

</script>



 

Add Pagination:

 

A small number of records are initially retrieved from the server and identified with the links to the Ajax pagination. The Ajax request is activated and sent to the server-side script when the paging link is clicked.

 

  • Use the Pagination calss creationLinks() function to view pagination links.

 

<div class="post-wrapper">

    <!-- Loading overlay -->

    <div class="loading-overlay"><div class="overlay-content">Loading...</div></div>


    <!-- Post list container -->

    <div id="postContent">

        <?php

        // Include pagination library file

        include_once 'Pagination.class.php';

      

        // Include database configuration file

        require_once 'dbConfig.php';

      

        // Set some useful configuration

        $baseURL = 'getData.php';

        $limit = 5;

      

        // Count of all records

        $query   = $db->query("SELECT COUNT(*) as rowNum FROM posts");

        $result  = $query->fetch_assoc();

        $rowCount= $result['rowNum'];

      

        // Initialize pagination class

        $pagConfig = array(

            'baseURL' => $baseURL,

            'totalRows' => $rowCount,

            'perPage' => $limit,

            'contentDiv' => 'postContent'

        );

        $pagination =  new Pagination($pagConfig);

      

        // Fetch records based on the limit

        $query = $db->query("SELECT * FROM posts ORDER BY id DESC LIMIT $limit");

      

        if($query->num_rows > 0){

        ?>

            <!-- Display posts list -->

            <div class="post-list">

            <?php while($row = $query->fetch_assoc()){ ?>

                <div class="list-item"><a href="javascript:void(0);"><?php echo $row["title"]; ?></a></div>

            <?php } ?>

            </div>


            <!-- Display pagination links -->

            <?php echo $pagination->createLinks(); ?>

        <?php } ?>

    </div>

</div>

 

Get Pagination Data (getData.php)

 

Ajax request loads the getData.php file to get the records from the database.

  •  
  • Based on the paging limit & offset, collect the data.

  • Render the list of data with links to pagination.

  • Return the data list HTML view.


 

<?php

if(isset($_POST['page'])){

    // Include pagination library file

    include_once 'Pagination.class.php';

  

    // Include database configuration file

    require_once 'dbConfig.php';

  

    // Set some useful configuration

    $baseURL = 'getData.php';

    $offset = !empty($_POST['page'])?$_POST['page']:0;

    $limit = 5;

  

    // Count of all records

    $query   = $db->query("SELECT COUNT(*) as rowNum FROM posts");

    $result  = $query->fetch_assoc();

    $rowCount= $result['rowNum'];

  

    // Initialize pagination class

    $pagConfig = array(

        'baseURL' => $baseURL,

        'totalRows' => $rowCount,

        'perPage' => $limit,

        'currentPage' => $offset,

        'contentDiv' => 'postContent'

    );

    $pagination =  new Pagination($pagConfig);


    // Fetch records based on the offset and limit

    $query = $db->query("SELECT * FROM posts ORDER BY id DESC LIMIT $offset,$limit");

  

    if($query->num_rows > 0){

    ?>

        <!-- Display posts list -->

        <div class="post-list">

        <?php while($row = $query->fetch_assoc()){ ?>

            <div class="list-item"><a href="javascript:void(0);"><?php echo $row["title"]; ?></a></div>

        <?php } ?>

        </div>

      

        <!-- Display pagination links -->

        <?php echo $pagination->createLinks(); ?>

<?php

    }

}

?>

LICENSE OF USE

You can use it for personal or commercial projects. You can't resell it partially or in this form.

PRODUCT INFO

Create Date : May 14, 2020

Updated Date : May 14, 2020

Ratings

Comments : 0

Downloads : 0