jQuery AJAX Pagination

In this tutorial, we are going to see simple code for pagination using jQuery AJAX and PHP. This code will have first, last, previous, next and other pagination links. On clicking each link it invokes AJAX handler to request for a limited page results from database.

The steps for implementing jQuery AJAX pagination are,

  1. Sending page request via AJAX.
  2. Calculate query limit to retrieve data.
  3. Create pagination links and apply styles.
  4. Show results and pagination links.

jquery_ajax_pagination

Download jQuery AJAX Pagination Source CodeLive Demo

Sending Page Request via AJAX

In this code, we are sending initial request for a page getresult.php. This page will do all server side functions and respond to the pagination request. AJAX handlers insert this response data into the target selectors.

<script>
function getresult(url) {    $.ajax({
	url: url,
	type: "GET",
	data:  {rowcount:$("#rowcount").val()},
	success: function(data){ $("#pagination").html(data); },
	error: function() {} 	        
   });
}
</script>
<div id="pagination">
<input type="hidden" name="rowcount" id="rowcount" />
</div>
<script>
getresult("getresult.php");
</script>

Calculate Query Limit

Since loading bulk of data takes much time, the pagination is for the quick retrieve/load. So, we have to calculate the start and end limit based on the page request. The code is,

require_once("dbcontroller.php");
require_once("pagination.class.php");
$db_handle = new DBController();
$perPage = new PerPage();

$sql = "SELECT * from php_interview_questions";
$paginationlink = "getresult.php?page=";					
$page = 1;
if(!empty($_GET["page"])) {
$page = $_GET["page"];
}

$start = ($page-1)*$perPage->perpage;
if($start < 0) $start = 0;

$query =  $sql . " limit " . $start . "," . $perPage->perpage; 
$faq = $db_handle->runQuery($query);

Create Pagination Links and Apply Styles

For creating total number of page links, we need to pass the database result count if found already. 

if(empty($_GET["rowcount"])) {
$_GET["rowcount"] = $db_handle->numRows($sql);
}
$perpageresult = $perPage->perpage($_GET["rowcount"], $paginationlink);

The function perpage will create all pagination links and apply styles based on the status of the page whether it is active or not applicable. The code is,

function perpage($count,$href) {  $output = '';  if(!isset($_GET["page"])) $_GET["page"] = 1;  if($this->perpage != 0) $pages = ceil($count/$this->perpage);  if($pages>1) {    if($_GET["page"] == 1)      $output = $output . '<span class="disabled"><<</span><span class="disabled"><</span>';    else      $output = $output . '<a class="link" onclick="getresult(\'' . $href . (1) . '\')" ><<</a><a class="link" onclick="getresult(\'' . $href . ($_GET["page"]-1) . '\')" ><</a>';
if(($_GET["page"]-3)>0) { if($_GET["page"] == 1) $output = $output . '<span id=1 class="current">1</span>'; else $output = $output . '<a class="link" onclick="getresult(\'' . $href . '1\')" >1</a>'; } if(($_GET["page"]-3)>1) { $output = $output . '...';
} for($i=($_GET["page"]-2); $i<=($_GET["page"]+2); $i++) { if($i<1) continue; if($i>$pages) break; if($_GET["page"] == $i) $output = $output . '<span id='.$i.' class="current">'.$i.'</span>'; else $output = $output . '<a class="link" onclick="getresult(\'' . $href . $i . '\')" >'.$i.'</a>'; } if(($pages-($_GET["page"]+2))>1) { $output = $output . '...'; } if(($pages-($_GET["page"]+2))>0) { if($_GET["page"] == $pages) $output = $output . '<span id=' . ($pages) .' class="current">' . ($pages) .'</span>'; else $output = $output . '<a class="link" onclick="getresult(\'' . $href . ($pages) .'\')" >' . ($pages) .'</a>'; } if($_GET["page"] < $pages) $output = $output . '<a class="link" onclick="getresult(\'' . $href . ($_GET["page"]+1) . '\')" >></a><a class="link" onclick="getresult(\'' . $href . ($pages) . '\')" >>></a>'; else $output = $output . '<span class="disabled">></span><span class="disabled">>></span>'; } return $output; }

Show Results and Pagination Links

Finally the requested PHP script will form the output HTML for printing database results and pagination link.

$output = '';
foreach($faq as $k=>$v) {
 $output .= '<div class="question"><input type="hidden" id="rowcount" name="rowcount" value="' . $_GET["rowcount"] . '" />' . $faq[$k]["question"] . '</div>';
 $output .= '<div class="answer">' . $faq[$k]["answer"] . '</div>';
}
if(!empty($perpageresult)) {
$output .= '<div id="pagelink">' . $perpageresult . '</div>';
}
print $output;

Data printed above will be read as an AJAX response and inserted into target selector.

success: function(data){
	$("#pagination").html(data);
}
<div id="pagination">
// AJAX Response will be Inserted
</div>

Download jQuery AJAX Pagination Source CodeLive Demo

This PHP code tutorial was published on July 10, 2014.

↑ Back to Top