Making Pagination with jQuery, AJAX and PHP

View: 360    Dowload: 0   Comment: 0   Post by: hanhga   Category: Php&mySql   Fields: Other

In this article, we’re going to explain how easy it is to paginate your data set using PHP and AJAX viajQuery. We’re also going to use the Silex framework for simplicity.

jQuery Logo

The data source

First off, we need some data to paginate!

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

For the purpose of this example we’re going to use MySQL, but of course we can swap this out easily forSQLite or any other RDBMS. We’re going to name our database example and the table will be namedpeople.

The backend

As we’re going to build our application on Silex, we need to install Silex using Composer first. Install it through composer with the command composer require silex/silex.

Next we need set up our index.php file, connect to the data source and select the database. We’re going to use PDO for this as it is easy to change to other database software later, and it also handles escaping user input (thus preventing SQL injection attacks). If you’re still stuck on the mysqli or even worse themysql extension, see this tutorial. We’re going to put the connection in the $app container so it’s easy to use later in our routes.

$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)
    );
};

Now that we’re connected to the database, we’re going to provide three routes in our app, which will enable;

  1. Retrieving the section of the result set we want to display
  2. Retrieving the total amount of rows in the result set
  3. Viewing the HTML frontend

The first route is as follows:

$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);
});

This enables our frontend to grab a subset of the result set from the database. Two parameters can be provided through the URI; one for the page number and one for how many rows should be on each page. The page number is used alongside the rows per page to work out which row in the result set we need to start retrieving data from.

In this example we are going to paginate all data from the table. However in a real application we will likely need to include a WHERE clause to filter the data returned. For example, if we wanted to just display people who are younger than 30, we would amend the above code to include a WHERE clause in the query:

$stmt = $app['db']->prepare(
    'SELECT
        `name`
    FROM
        `people`
    WHERE
        `age` < 30
    ORDER BY
        `name`
    LIMIT
        :from, :total_rows'
);

The query is using a prepared statement to insert the variables for which page number has been requested and how many rows to output per page. These are provided in the URI and then dynamically inserted into a LIMIT clause in the SQL query.

The second route provides the ability to execute a query to return the total amount of rows in the table. This is important because we want to utilize page number links on the frontend. That route should look like this:

$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);
});

Here we are making use of an aggregate SQL function called COUNT(). This is a GROUP BY function – meaning that it will group the selected rows together to provide a single row. In this case it provides a sum total of all selected rows as an integer.

Another important backend feature to note is that the data fetching routes should return as JSON, as this will ease the integration into the frontend. Silex takes care of this for us using the JSON helper method.

The last route is simply instructing the root URI to output an HTML page.

$app->get('/', function () use ($app) {
    return file_get_contents(__DIR__.'/../resources/views/index.html');
});

Which brings us to…

The frontend

Now the fun bit!

We need to make sure our frontend includes jQuery and has a container for both the page number links and the data itself.

<ul id="rows"></ul>
<ul id="page-numbers"></ul>

<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>

In this example we’re going to use <ul>s, however in a real application we may want to use a <table>for the data (especially important if we want to display more than one piece of information per row).

We’ll need two custom functions in Javascript; one to fetch a specific page, and one to initialize the page number links. In our example we’ve also done a little bit of set up before we get to the main section of code:

var rows_per_page = 3;
var total_rows;

This initializes two global variables for the number of rows we want to show per page and the total amount of rows in the table (the latter will be fetched via AJAX shortly).

To initialize the page number links we’ll need to make an AJAX call to our PHP script to fetch the total amount of rows in the table. Then we’ll use the success function callback to inject the HTML to link to each page into our page number links container depending on the total amount of rows. It should look something like this:

function initPageNumbers()
{
    //Get total rows number
    $.get('data/countrows', function(data){
        total_rows = parseInt(data.total_rows);

        //Loop through every available page and output a page link
        var count = 1;
        for(var x = 0;  x < total_rows; x += rows_per_page)
        {
            $('#page-numbers').append('<li><a href="#'+count+'" onclick="getPage('+count+');">'+count+'</a></li>');
            count++;
        }
    });
}

Note that we’re injecting the HTML for the page links with a Javascript function call already attached. This means that clicking those links will trigger our page fetching function without us attaching a click event manually. Also note that the href attribute is set to a hash fragment with the page number – this means that the URI will be modified to reflect which page number we’re viewing.

The function for fetching a specific page also uses an AJAX call, but has a few key differences;

function getPage(page_num)
{
    //Clear the existing data view
    $('#rows').html('');

    //Get subset of data
    $.get('data/page/'+page_num+'/'+rows_per_page, function(data){
        //Loop through each row and output the data
        $(data).each(function(){
            $('#rows').append('<li>'+this.name+'</li>');
        });
    }); 
}

The first difference to note is that the container is cleared first using jQuery’s html() function. This is because this function will be called multiple times, and needs a blank slate to work from each time. The second difference is that the data itself is looped through in the success function callback. This is done using the very useful jQuery each() function.

Both functions use the get() jQuery AJAX shorthand function for making a HTTP GET request. The jQuery ajax() function could be used instead, which allows for more configuration, but the shorthand is just fine for this example.

The getPage() function also differs from the initPageNumbers() function as it passes two parameters along with the HTTP GET request. These are provided in an object as the second parameter of the get() function call. These are then processed by the PHP script as defined previously.

Now all that’s left is to set up the page initialization logic. To do this we’ll be using the jQuery ready()function;

$(document).ready(function(){
    //Set up the page number links
    initPageNumbers();

    //Set the default page number
    var page_num = 1;

    //If there's a hash fragment specifying a page number
    if(window.location.hash !== '')
    {
        //Get the hash fragment as an integer
        var hash_num = parseInt(window.location.hash.substring(1));

        //If the hash fragment integer is valid
        if(hash_num > 0)
        {
            //Overwrite the default page number with the user supplied number
            page_num = hash_num;
        }
    }

    //Load the first page
    getPage(page_num);
});

This calls our page number initialisation function and fetches a page of the result set to display.

If a hash fragment has been provided on the end of the URI then this will be parsed into a page number and set as the page to show, otherwise page 1 is shown by default. This hash fragment functionality lets search engines index our individual pages rather than just the first page. It also allows us to provide external links directly to a specific page number.

Making Pagination with jQuery, AJAX and PHP

In this article, we’re going to explain how easy it is to paginate your data set using PHP and AJAX viajQuery. We’re also going to use the Silex framework for simplicity.

Posted on 09-03-2016 

Comment:

To comment you must be logged in members.

Files with category

  • SimpleXML is a PHP extension that allows us to easily manipulate and get XML data

    SimpleXML is a PHP extension that allows us to easily manipulate and get XML data

    View: 276    Download: 0   Comment: 0

    Category: Php&mySql     Fields: none

    SimpleXML provides an easy way of getting an element's name, attributes and textual content if you know the XML document's structure or layout. SimpleXML turns an XML document into a data structure you can iterate through like a collection of arrays...

  • How to use the PHP download file script? Class Download PHP

    How to use the PHP download file script? Class Download PHP

    View: 181    Download: 1   Comment: 0

    Category: Php&mySql     Fields: Other

    This is my favorite PHP download script. I’ve used a different more simple method until a client wanted to be able to allow their site visitors to download a large file from a password protected directory. The PHP script works on Apache web servers...

  • Installing OCI8 & PHP 7.2 on RHEL or CentOS 6

    Installing OCI8 & PHP 7.2 on RHEL or CentOS 6

    View: 315    Download: 0   Comment: 0

    Category: Php&mySql     Fields: Other

    You’ll need to stop Apache (web server) using the following command. In any Linux commands I show in this article, it presumes you aren’t logged in as the root user, so you will need to use sudo to issue privileged commands.

  • PHP source code: get content of google search

    PHP source code: get content of google search

    View: 264    Download: 2   Comment: 0

    Category: Php&mySql     Fields: Other

    How to get the results of google search and display on your website. This PHP code can do that. Refer to the following code.

  • PHP as a Scripting Language for C#

    PHP as a Scripting Language for C#

    View: 194    Download: 0   Comment: 0

    Category: Php&mySql     Fields: none

    When creating .NET applications (including desktop and web applications), it may be useful to allow extending the application using some scripting language. The users of the application can write simple scripts to configure the application, modify...

  • How to Picking the Brains of Your Customers with Microsoft’s Text Analytics

    How to Picking the Brains of Your Customers with Microsoft’s Text Analytics

    View: 4281    Download: 0   Comment: 0

    Category: Php&mySql     Fields: Other

    With the explosion of machine learning services in recent years, it has become easier than ever for developers to create “smart apps”. In this article, I’ll introduce you to Microsoft’s offering for providing machine-learning capabilities to apps.

  • How to MySqli Tutorial PHP MySqli Extension

    How to MySqli Tutorial PHP MySqli Extension

    View: 589    Download: 0   Comment: 0

    Category: Php&mySql     Fields: Other

    PHP provides three api to connect mysql Database.

  • Make Laravel Artisan Commands

    Make Laravel Artisan Commands

    View: 540    Download: 0   Comment: 0

    Category: Php&mySql     Fields: Other

    Artisan is the command line tool used in Laravel framework. It offers a bunch of useful command that can help you develop application quickly. Apart from Artisan available commands, you can create your own custom commands to improve your workflow.

 
File suggestion for you
File top downloads
Codetitle - library source code to share, download the file to the community
Copyright © 2018. All rights reserved. codetitle Develope by Vinagon .Ltd