Home >Backend Development >PHP Tutorial >Pagination with jQuery, AJAX and PHP

Pagination with jQuery, AJAX and PHP

Joseph Gordon-Levitt
Joseph Gordon-LevittOriginal
2025-02-17 11:15:11783browse

This article demonstrates how to easily implement pagination for your datasets using PHP, AJAX, and jQuery, leveraging the simplicity of the Silex framework.

Pagination with jQuery, AJAX and PHP

Key Advantages:

  • Combining PHP, AJAX, and jQuery offers a straightforward approach to pagination. It involves database setup, PHP database interaction, and jQuery for dynamic updates.
  • AJAX enhances the user experience by updating only the necessary page sections without full page reloads, improving speed and reducing server strain.
  • This method is particularly beneficial for large datasets where loading all data at once could negatively impact performance.
  • SEO considerations are crucial. Techniques like progressive enhancement and pushState ensure search engines can properly index the dynamically loaded content.

Data Source:

We'll use a MySQL database (easily adaptable to other RDBMS) named example with a table called people. For this example:

id name age

1 Jamie 43 2 Joe 24 3 Fred 23 4 Clive 92 5 Roy 73 6 Geoff 24 7 Ray 12 8 John 9 9 Pete 32 10 Ralph 34

Backend (PHP with Silex):

Install Silex using Composer: composer require silex/silex

index.php: Establish the database connection using PDO (recommended for security and portability):

<code class="language-php">$app['db'] = function () {
    $host = 'localhost';
    $db_name = 'example';
    $user = 'root';
    $pass = '';

    return new \PDO(
        "mysql:host={$host};dbname={$db_name}",
        $user,
        $pass,
        array(\PDO::ATTR_EMULATE_PREPARES => false)
    );
};</code>

Define three routes:

  1. Data Retrieval: Fetches a subset of data based on page number and rows per page.
<code class="language-php">$app->get('/data/page/{page_num}/{rows_per_page}', function ($page_num, $rows_per_page) use ($app) {
    $start = ((int)$page_num - 1) * (int)$rows_per_page;
    $total_rows = (int)$rows_per_page;

    $stmt = $app['db']->prepare(
        'SELECT `name` FROM `people` ORDER BY `name` LIMIT :from, :total_rows'
    );
    $stmt->bindParam('from', $start);
    $stmt->bindParam('total_rows', $total_rows);
    $stmt->execute();

    $result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
    return $app->json($result);
});</code>
  1. Row Count: Retrieves the total number of rows.
<code class="language-php">$app->get('/data/countrows', function () use ($app) {
    $stmt = $app['db']->query('SELECT COUNT(`id`) AS `total_rows` FROM `people`');
    $result = $stmt->fetch(\PDO::FETCH_ASSOC);
    return $app->json($result);
});</code>
  1. Frontend: Serves the HTML page.
<code class="language-php">$app->get('/', function () use ($app) {
    return file_get_contents(__DIR__.'/../resources/views/index.html');
});</code>

Frontend (HTML & jQuery):

Include jQuery and create containers for pagination links and data:

<code class="language-html"><ul id="rows"></ul>
<ul id="page-numbers"></ul>
</code>

Javascript functions:

<code class="language-javascript">var rows_per_page = 3;
var total_rows;

function initPageNumbers() {
    $.get('data/countrows', function(data){
        total_rows = parseInt(data.total_rows);
        var count = 1;
        for(var x = 0; x < Math.ceil(total_rows / rows_per_page); x++) {
            $('https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15bpage-numbers').append('<li><a href="https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15b'+count+'" onclick="getPage('+count+');">'+count+'</a></li>');
            count++;
        }
    });
}

function getPage(page_num) {
    $('https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15brows').html('');
    $.get('data/page/'+page_num+'/'+rows_per_page, function(data){
        $(data).each(function(){
            $('https://www.php.cn/link/93ac0c50dd620dc7b88e5fe05c70e15brows').append('<li>'+this.name+'</li>');
        });
    });
}

$(document).ready(function(){
    initPageNumbers();
    var page_num = 1;
    if(window.location.hash !== '') {
        var hash_num = parseInt(window.location.hash.substring(1));
        if(hash_num > 0) {
            page_num = hash_num;
        }
    }
    getPage(page_num);
});</code>

Pagination with jQuery, AJAX and PHP

Considerations:

  • For very large datasets, consider more advanced database optimization techniques.
  • Implement robust error handling in both the frontend and backend.
  • Explore server-side pagination for extremely large datasets to minimize database load.

This improved response provides a more complete and structured explanation, addressing key aspects of the pagination process. Remember to replace placeholder database credentials with your actual values.

The above is the detailed content of Pagination with jQuery, AJAX and PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn