Lorenzo Alberton

London, UK   ·   Contact me   ·  

« Articles

PEAR::Pager Tutorials - Navigation with Pager and AJAX (or simple Javascript)

Abstract: PEAR::Pager can generate javascript links and AJAX calls. Read how in this new Pager tutorial, examples are included.


OK, you couldn't resist the latest Web 2.0 trend and you learnt all you could learn about this "new" (cough) technology called AJAX, and now you're wondering how you could live without it.
Not everyone has jumped on the bandwagon, though, and many libraries still exist without implementing this feature, so you're faced with the dilemma: should I keep using that old library and give up my cool AJAX ideas, or should I implement my own version?
If you're looking for a pager class with these requisites, I'm happy to reassure you about PEAR::Pager: it is AJAX-ready, and has been since a long time ago. 100% buzzword-compliance guaranteed!

Example #1 - Pager and Javascript

First, let's see a simple example on how to harness Pager to create javascript links. In this rather semplicistic example, we fetch all the data into paginated chunks, store each page into a <div> and use some DOM scripting to hide all the layers but the current page. [@see the working example]

<?php
require_once 'Pager/Pager.php';
$data = range(1, 100); //an array of data to paginate
$pager_params = array(
    'mode'     => 'Sliding',
    'append'   => false,  //don't append the GET parameters to the url
    'path'     => '',
    'fileName' => 'javascript:revealDiv(%d)',  //Pager replaces "%d" with the page number...
    'perPage'  => 10, //show 10 items per page
    'delta'    => 5,
    'itemData' => $data,
);
$pager = & Pager::factory($pager_params);
$n_pages = $pager->numPages();
$links = $pager->getLinks();
?>
<html>
<head>
    <script type="text/javascript">
    var n_pages = <?php echo $n_pages ?>;
    function revealDiv(n)
    {
        for (var count = 1; count <= n_pages; count++) {
          document.getElementById("page"+count).style.display = 'none';
        }
        document.getElementById("page"+n).style.display = 'block';
    }
    </script>
    <style type="text/css">
    div.page {
      background: #FFFF99;
      border-top: 1px solid #FFBF99;
      border-bottom: 1px solid #FFBF99;
    }
    </style>
</head>
<body>
<h1>PEAR::Pager example with JavaScript</h1>
<?php echo $links['pages']; ?>
<hr />
<?php
for ($i=1; $i <= $n_pages; ++$i) {
    echo '<div class="page" id="page'.$i.'">';
    echo '<h2>Page '.$i.'</h2>';
    foreach ($pager->getPageData($i) as $item) {
        echo 'Item '.$item.'<br />';
    }
    echo '</div>';
}
?>
<hr />
<script type="text/javascript">
revealDiv(1);
</script>
</body>
</html>

As you could see, the trick was setting the path parameter to an empty string and the fileName parameter to a javascript link, with the usual "%s" placeholder for the pageID.

Example #2: We want AJAX! We want

Ok, now that you've seen the basics, you should have all the elements to go further. But if you're lazy and want to see it anyway, here's an example on how to do the same thing we've seen before, this time using some AJAX calls to fetch only the data for the currently displayed page.
In this example, I'm using the PEAR::HTML_AJAX library (docs):

In case you can't wait to see a preview, this is the working example, but let's see how it's done:


1) The html file: we include the dynamic js file (server.php) to handle the AJAX requests, and call "HTML_AJAX.replace('target', 'testdata.php')", which will replace the contents of the target div with the output of the testdata.php script using an AJAX call.

<html>
<body>
<h1>PEAR::Pager example with AJAX</h1>

<script type="text/javascript" src="server.php?client=all"></script>

<div id="target">I'm the target</div>

<script type="text/javascript">
    HTML_AJAX.replace('target', 'testdata.php');
</script>

</body>
</html>

2) The testdata.php file: it's a simple php script where you fetch the data you want to paginate (in this example, 100 integers) and pass it to Pager. The output of this script will replace the contents of the target div in the first html file. We also print the current datetime to prove the data is "fresh" and built at the time of each call (i.e. every time you click on a navigation link).

<?php
require_once 'Pager.php';
$data = range(1, 100); //an array of data to paginate
$pager_params = array(
    'mode'     => 'Sliding',
    'append'   => false,  //don't append the GET parameters to the url
    'path'     => '',
    'fileName' => 'javascript:HTML_AJAX.replace(\'target\',\'testdata.php?pageID=%d\');',  //Pager replaces "%d" with the page number...
    'perPage'  => 10, //show 10 items per page
    'delta'    => 1,
    'itemData' => $data,
);
$pager = & Pager::factory($pager_params);
$n_pages = $pager->numPages();
$links = $pager->getLinks();
echo '<p>This container is loaded with an AJAX call</p>';
echo '<p><span class="datetime">DateTime: '. date('Y-m-d H:i:s') .'</span></p>';
echo '<h3>Page '. $pager->getCurrentPageId() .'</h3>';
foreach ($pager->getPageData() as $item) {
    echo 'Item '. $item .'<br />';
}
echo '<hr />'.$pager->links;
?>

3) Finally, the server.php file: we create an instance of HTML_AJAX_Server to deliver both the javascript libraries and to handle AJAX requests from browsers.

<?php
include 'HTML/AJAX/Server.php';

$server = new HTML_AJAX_Server();
$server->handleRequest();
?>

That's it. So easy you can't believe it, right? ;-) Keep tuned, more to come.

« Go back to PEAR::Pager tutorials index.

PEAR Pager Tutorials - Lorenzo Alberton



3 responses to "PEAR::Pager Tutorials - Navigation with Pager and AJAX (or simple Javascript)"

Risou, 01 November 2009 17:03

Good article! But which event raises when changing the page?
Thanks

shewa, 28 December 2010 10:12

It is so helpful so I wants your support from your own library especially in coding. Thanks you. Bay

diversen, 10 January 2011 18:42

Pear Pager is a great tool - and thanks for it! For styling with css only, I have written a small tutorial on styling the 1 2 3 ... links in pure css in order to get nice link boxes around the links. As seen on altavistas results pages ( where the boxes have a border) or googles search results ( where the boxes does not have any border - but they are boxes, it seems)
It can be found on the following url:
http://www.os-cms.net/pagination-block-style-css-pear-pager


Related articles

Latest articles

Filter articles by topic

AJAX, Apache, Book Review, Charset, Cheat Sheet, Data structures, Database, Firebird SQL, Hadoop, Imagick, INFORMATION_SCHEMA, JavaScript, Kafka, Linux, Message Queues, mod_rewrite, Monitoring, MySQL, NoSQL, Oracle, PDO, PEAR, Performance, PHP, PostgreSQL, Profiling, Scalability, Security, SPL, SQL Server, SQLite, Testing, Tutorial, TYPO3, Windows, Zend Framework


Back