2/3/2012 Update: PHP AJAX Pagination (PDO Version)
2/2/2012 Update: PHP AJAX Pagination (MySQLi Version)
Hi there! Today we are going to do a very simple yet useful script for your web apps:
- This code will load the paginated data via AJAX (We'll have some loader image to make it look good and user friendly).
- Paginated data was returned by our PHP script with the help of a Modified PS_Pagination Class (Yes, I modified it myself since I want to use this Awesome pagination class with jQuery.)
![]() |
| Easy browsing of pages |
images/ajax-loader.gif - for our loader animation
js/jquery-1.4.js - our favorite javascript library
libs/ps_pagination.php - the pagination class I modified
styles/style.css - style for our table data and page number navigation
config_open_db.php - for database connection
index.php - our main UI
search_results.php - returns the data that will be returned to index.php
js/jquery-1.4.js - our favorite javascript library
libs/ps_pagination.php - the pagination class I modified
styles/style.css - style for our table data and page number navigation
config_open_db.php - for database connection
index.php - our main UI
search_results.php - returns the data that will be returned to index.php
Step 1:Prepare you data. We're gonna use the following table structure. Just add you own data.
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(32) NOT NULL,
`lastname` varchar(32) NOT NULL,
`email` varchar(32) NOT NULL,
`username` varchar(32) NOT NULL,
`password` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
)
`id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(32) NOT NULL,
`lastname` varchar(32) NOT NULL,
`email` varchar(32) NOT NULL,
`username` varchar(32) NOT NULL,
`password` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
)
Step 2: Prepare your loader image, jQuery library and our modified PS Pagination library. I will not copy the pagination library codes here. You may just download the code package of this tutorial and you may compare it to its original code by downloading it here.
Step 3: Our User Interface will be represented by our index.php file:
<html>
<head>
<title>Paginating Your Data with AJAX and Awesome PHP Pagination Class</title>
</head>
<body>
<div id='retrieved-data'>
<!--
this is where data will be shown
-->
<img src="images/ajax-loader.gif" />
</div>
<script type = "text/javascript" src = "js/jquery-1.4.js"></script>
<script type = "text/javascript">
$(function() {
//call the function onload, default to page 1
getdata( 1 );
});
function getdata( pageno ){
var targetURL = 'search_results.php?page=' + pageno; //page no was used internally by the pagination class, its value was supplied by our navigation buttons
$('#retrieved-data').html('<p><img src="images/ajax-loader.gif" /></p>');
$('#retrieved-data').load( targetURL ).hide().fadeIn('slow');
}
</script>
</body>
</html>
<head>
<title>Paginating Your Data with AJAX and Awesome PHP Pagination Class</title>
</head>
<body>
<div id='retrieved-data'>
<!--
this is where data will be shown
-->
<img src="images/ajax-loader.gif" />
</div>
<script type = "text/javascript" src = "js/jquery-1.4.js"></script>
<script type = "text/javascript">
$(function() {
//call the function onload, default to page 1
getdata( 1 );
});
function getdata( pageno ){
var targetURL = 'search_results.php?page=' + pageno; //page no was used internally by the pagination class, its value was supplied by our navigation buttons
$('#retrieved-data').html('<p><img src="images/ajax-loader.gif" /></p>');
$('#retrieved-data').load( targetURL ).hide().fadeIn('slow');
}
</script>
</body>
</html>
Step 4: This will be the code inside our search_results.php file where our modified pagination class was used.
<!-- include style -->
<link rel="stylesheet" type="text/css" href="styles/style.css" />
<?php
//open database
include 'config_open_db.php';
//include our awesome pagination
//class (library)
include 'libs/ps_pagination.php';
//query all data anyway you want
$sql = "select * from users ORDER BY firstname DESC";
//execute query and get and
$rs = mysql_query( $sql ) or die('Database Error: ' . mysql_error() . ' ' . $sql );
//now, where gonna use our pagination class
//this is a significant part of our pagination
//i will explain the PS_Pagination parameters
//$conn is a variable from our config_open_db.php
//$sql is our sql statement above
//3 is the number of records retrieved per page
//4 is the number of page numbers rendered below
//null - i used null since in dont have any other
//parameters to pass (i.e. param1=valu1¶m2=value2)
//you can use this if you're gonna use this class for search
//results since you will have to pass search keywords
$pager = new PS_Pagination( $conn, $sql, 3, 4, null );
//our pagination class will render new
//recordset (search results now are limited
//for pagination)
$rs = $pager->paginate();
//get retrieved rows to check if
//there are retrieved data
$num = mysql_num_rows( $rs );
if($num >= 1 ){
//creating our table header
echo "<table id='my-tbl'>";
echo "<tr>";
echo "<th>Firstname</th>";
echo "<th>Lastname</th>";
echo "<th>Email</th>";
echo "</tr>";
//looping through the records retrieved
while($row = mysql_fetch_array( $rs )){
echo "<tr class='data-tr' align='center'>";
echo "<td>{$row['firstname']}</td>";
echo "<td>{$row['lastname']}</td>";
echo "<td>{$row['email']}</td>";
echo "</tr>";
}
echo "</table>";
}else{
//if no records found
echo "No records found!";
}
//page-nav class to control
//the appearance of our page
//number navigation
echo "<div class='page-nav'>";
//display our page number navigation
echo $pager->renderFullNav();
echo "</div>";
?>
<link rel="stylesheet" type="text/css" href="styles/style.css" />
<?php
//open database
include 'config_open_db.php';
//include our awesome pagination
//class (library)
include 'libs/ps_pagination.php';
//query all data anyway you want
$sql = "select * from users ORDER BY firstname DESC";
//execute query and get and
$rs = mysql_query( $sql ) or die('Database Error: ' . mysql_error() . ' ' . $sql );
//now, where gonna use our pagination class
//this is a significant part of our pagination
//i will explain the PS_Pagination parameters
//$conn is a variable from our config_open_db.php
//$sql is our sql statement above
//3 is the number of records retrieved per page
//4 is the number of page numbers rendered below
//null - i used null since in dont have any other
//parameters to pass (i.e. param1=valu1¶m2=value2)
//you can use this if you're gonna use this class for search
//results since you will have to pass search keywords
$pager = new PS_Pagination( $conn, $sql, 3, 4, null );
//our pagination class will render new
//recordset (search results now are limited
//for pagination)
$rs = $pager->paginate();
//get retrieved rows to check if
//there are retrieved data
$num = mysql_num_rows( $rs );
if($num >= 1 ){
//creating our table header
echo "<table id='my-tbl'>";
echo "<tr>";
echo "<th>Firstname</th>";
echo "<th>Lastname</th>";
echo "<th>Email</th>";
echo "</tr>";
//looping through the records retrieved
while($row = mysql_fetch_array( $rs )){
echo "<tr class='data-tr' align='center'>";
echo "<td>{$row['firstname']}</td>";
echo "<td>{$row['lastname']}</td>";
echo "<td>{$row['email']}</td>";
echo "</tr>";
}
echo "</table>";
}else{
//if no records found
echo "No records found!";
}
//page-nav class to control
//the appearance of our page
//number navigation
echo "<div class='page-nav'>";
//display our page number navigation
echo $pager->renderFullNav();
echo "</div>";
?>
Step 5: As for the CSS, I used the following:
<style type='text/css'>
/*you can change you table style here*/
#my-tbl {
background-color: #FFF;
color: black;
padding: 5px;
width: 700px;
border: thin solid red;
}
#th{
background-color: #000;
color: #FFF;
padding: 10px;
border-bottom: thin solid #000;
}
.data-tr{
background-color: #FFF;
color: #000;
border-bottom: thin solid #000;
}
.data-tr:hover {
background-color: #FAEFCF;
color: black;
padding: 5px;
border-bottom: thin solid #000;
}
.data-tr td{
padding: 10px;
margin: 0px;
}
/* you can change page navigation here*/
.page-nav{
margin: 10px 0 0 0;
padding: 8px;
}
.page-nav a{
border: none;
padding: 8px;
text-decoration: none;
background-color: #FFC;
border: thin solid #FC0;
color: #000;
}
.page-nav a:hover{
border: thin solid #FC0;
background-color: #FC0;
color: #fff;
}
/*this is the style for selected page number*/
.page_link{
padding: 8px;
}
</style>
/*you can change you table style here*/
#my-tbl {
background-color: #FFF;
color: black;
padding: 5px;
width: 700px;
border: thin solid red;
}
#th{
background-color: #000;
color: #FFF;
padding: 10px;
border-bottom: thin solid #000;
}
.data-tr{
background-color: #FFF;
color: #000;
border-bottom: thin solid #000;
}
.data-tr:hover {
background-color: #FAEFCF;
color: black;
padding: 5px;
border-bottom: thin solid #000;
}
.data-tr td{
padding: 10px;
margin: 0px;
}
/* you can change page navigation here*/
.page-nav{
margin: 10px 0 0 0;
padding: 8px;
}
.page-nav a{
border: none;
padding: 8px;
text-decoration: none;
background-color: #FFC;
border: thin solid #FC0;
color: #000;
}
.page-nav a:hover{
border: thin solid #FC0;
background-color: #FC0;
color: #fff;
}
/*this is the style for selected page number*/
.page_link{
padding: 8px;
}
</style>
Well that's it. :)
For FREE programming tutorials, enter your email below and subscribe! :)





33 comments:
Wow nice tut, ninja mike! Napaka detailed! :)
Thanks sir :)
Great script!. Just one weird issue. The css on my target page is a little goofy when going through the index page but looks just fine when I go directly to it.
Any thoughts?
Thanks again for the great script.
Ty =)
@Anonymous_1: Can you give me a link to a screenshot or page of your problem?
@Anonymous_2: You're welcome. :)
If you were a girl, I will definitely marry you. I love you... Great work buddy, keep it up...
Hahahahahaha! Thanks @Anonymous! :)
hi i do like your cool and easy pagination class..however is it possible to have pages that would have been edited to have a different link colour.
For example say i am paginating user comments and have 100 pages of comments and i have 20 records per page and 5 page links at the bottom.How can i have say the page 3 link show a different colour to indicate that a comment has been made on that page?
i am new to php and ajax
Thanks man, look at the bottom part of my CSS code, you'll see the .page_link class. That class was used for the current/selected page. You can play around with that to change the link colour/style. :)
I keep getting an error when I click the links to go to another page:
"Uncaught ReferenceError: getdata is not defined"
URL:http://www.25idtacops.com/pbsvss.php
@Joe: I just saw you got it working now, nice. :)
wooooooow, great man! thank you so much, i am immediately implementing this on my website! this if of great help! i was looking for a dynamic pagination solution using ajax, and there you go... you have it :) thanks!
HI, I try to use this magnifique pagination with MSSQL but i have on error in LIMIT
$rs = @mysql_query($this->sql . ” LIMIT {$this->offset}, {$this->rows_per_page}” );
I change mysql_query for mssql_query and LIMIT to TOP, but i have a error:
Warning: mssql_fetch_array(): supplied argument is not a valid MS SQL-result resource
Can you Help me???
@psihologie: You're welcome. :)
@Joni Wilson: Sorry dude I'm not using MSSQL and not familiar with its syntax..
MSSQL does not support the SQL Limit statement. Try using TOP instead.
Hello thanks for your script. Any clue abut how to use it with a MySQLi connection? I'm always getting Fatal error: Call to a member function query() on a non-object but I don't really know how to get rid of it.
Many thanks
Franz
Hi I think this is just the ticket for what I'm looking for but getting an error.
Method name must be a string..line 111
Line 111 $result=$pager->$paginate();
Line 112 $num=mysql_num_rows($results);
I cannot see anything wrong..
Any help would be grateful.
Nice code - I will try and see if I can get it working in a project I currently have.
Helen Neely
ease on implementing and configuration. This code rocks!
Thanks ninja guy
sup... got any hints on what to do when using it with jQuery mobile? teh html gets injected properly but it doesn't get styled like the other elements on the page. some refresh trigger or something? cheers
I like your script ,I would like to implement this script to more then 10 pages.Its is posiple to pass the filename to the javascript function getdata(2) .
I have rewritten your code to work with MongoDB. It works great. But I have a problem now. I had some ajax request and they don't work.
For example, I can't get this:
var row = $(this).parent().parent();
Probably because the table is not render and I can't find elements. What should I do?
Can anybody re-upload please?
The download isn't working.
Thanks.
download worked fine for me.
Nice script! Learned a lot from it, Im new to dealing with ajax
Dear Sir,
$sql=mysql_Query(“select * from ads where cityname=’$city’ and type=’$sid’ order by id desc”);
Whenever i use this sql statment in php it work great in first page but next page i got errors
like:
Undefined index: subcatn in D:\xampp\htdocs\test\db\ads1.php on line 17
Notice: Undefined index: cityn in D:\xampp\htdocs\test\db\ads1.php on line 18
Notice: Undefined index: mcn in D:\xampp\htdocs\test\db\ads1.php on line 19
Query returned zero rows.
What i do now?
thanks for advance
@Muhammad Umer: Hi there! Please double check your database fields, subcatn, cityn and mcn seems like they does not exist.
Dear Respected Mike.
I am very tahnkful for your kind reply. but subcatn and cityn and mcn just the values that get from users the database fields is cityname, and type.
i show you whlo script that is here:
'.$mcn.'->'.$sid;
?>
setDebug(true);
if ($result){
$rs = $pager->paginate();
if(!$rs) die(mysql_error());
while ($row=mysql_fetch_array($rs)){
Retrive Data here
echo $pager->renderFullNav();
echo '
';
echo "Post Ad";
?>
whenever i use simple sql query like
"select * from ads" then its worked great but when i use "select * from ads where cityname=$city" then in first page working good but when i click second page error occor Notice: Undefined index: cityn in D:\xampp\htdocs\test\db\ads1.php
This is actual prob with me please help me i will very thankful to you.
Dear Mike,
your pagination is not working when we use variables in sql statement.
@Muhammad Umer: Glad to know it is now working... By the way, you can paste your code next time in pastebin and link it here so we can see it properly, blogger does not allow code to be posted in comments..
Dear Mike,
I have posted my code in pastbin please now tell me where is problem my project is stuck there. Please help me.
you can find code here http://pastebin.ca/2308539
@Muhammad - are you sure you included your parameters such as cityn on your javascript, like in my code, i only have 'page' as the parameter.
var targetURL = 'search_results.php?page=' + pageno;
yours should be something like:
var targetURL = 'search_results.php?page=' + pageno + '&cityn=php_generated_cityn_here';
Sir i used javascript in my page and also give the value of variable but still not working
i am using code like
var targetURL = 'search_results.php?page=' + pageno + '&cityn=$city';
Post a Comment
You can use http://pastebin.com/ or http://jsfiddle.net/ if you want to comment some codes.