Bootstrap Pagination Using Ajax and PHP

Twitter Bootstrap is the very popular CSS template framework best for modern responsive web design. Bootstrap provides various templates of website design materials including table list, form, content grid, button, graph, model, and so on. In this tutorial, we will take a feature of bootstrap to customize for more user-friendly. Bootstrap only provides the template of table design with static data. With this template, we will make it more flexible with PHP and Ajax. Let’s see how to make it works.

INSTRUCTION

HTML Layout

<!--START HTML TBALE LAYOUT-->
<div>
<!--START HTML STRING SEARCH INPUT-->
<form role="form" id="[LISTNAME]_frm">
<div class="form-group">                        
<div class="input-group custom-search-form">
<input type="text" id="[LISTNAME]_search_txt" class="form-control" placeholder="">
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="[LISTNAME]_search_btn">
<i class="fa fa-search"></i>
</button>
</span>
</div>
</div>
</form>
<!--END HTML STRING SEARCH INPUT-->
<div>
<!--START HTML NUMBER OF ITEM PER PAGE BLOCK-->
<div style="float:right;">
<label>
<div style="display:inline-block">Rows per page: </div>
<div style="display:inline-block">
<select class="form-control input-sm" id="nav_rowsPerPage">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</select>
</div>
</label>
</div>
<!--END HTML NUMBER OF ITEM PER PAGE BLOCK-->                                    
<!--START TOTAL ITEM INFO BLOCK-->
<div style="float:left;">
<label>
<span id="nav_info"></span>
</label>
</div>
<!--END TOTAL ITEM INFO BLOCK-->
</div>
<div class="clearfix"></div>                                
<!--START RESPONSIVE TBALE-->
<div class="table-responsive" id="[LISTNAME]_tbl_cover">
<table class="table table-striped table-bordered table-hover" id="[LISTNAME]_tbl">
<thead>
<tr>
<th>[COL1]</th>
<th>[COL2]</th>
<th>[COL3]</th>
</tr>
</thead>
<tbody>                                            
</tbody>
</table>
</div>
<!--END RESPONSIVE TBALE-->                                
<!--START PAGINATION BUTTON-->
<div class="form-group" style="width:100%; text-align:center;">
<button type="submit" class="btn btn-default" id="nav_first"><i class="fa fa-fast-backward"></i> First</button>
<button type="submit" class="btn btn-default" id="nav_prev"><i class="fa fa-caret-left"></i> Prev</button>
<select class="nav_pageNum btn btn-default" id="nav_currentPage"></select>
<button type="submit" class="btn btn-default" id="nav_next">Next <i class="fa fa-caret-right"></i></button>
<button type="submit" class="btn btn-default" id="nav_last">Last <i class="fa fa-fast-forward"></i></button>
</div>
<!--END PAGINATION BUTTON-->
</div>
<!--END HTML TBALE LAYOUT-->

This html layout contains all the required elements for the pagination display. The html includes:

  • Searching text box (other search input can be added)
  • Number per page select box
  • Page information block
  • Bootstrap table
  • Pagination button

To get bootstrap library, let’s follow this: http://getbootstrap.com/getting-started/#download

Javascript

$(document).ready(function(e) {
//SHOW LIST WHEN DO STRING SEARCH
$("#[LISTNAME]_search_btn").click(function(){showList('');});						
//--- start navigation btn
$("#nav_first").click(function(e){showList('first');});
$("#nav_prev").click(function(e){showList('prev');});
$("#nav_next").click(function(e){showList('next');});
$("#nav_last").click(function(e){showList('last');});
$("#nav_rowsPerPage").change(function(e){showList('');});
$("#nav_currentPage").change(function(e){showList('goto');});
//--- end navigation btn
//SHOW LIST WHEN CALLED BY OTHER BUTTON [ADD NEW ITEM, THEN RELOAD LIST]
$("#[LISTNAME]_frm").submit(function(){showList(); return false;});						
//START SHOWING LIST				
showList('');						
// START LIST FUNCTION
function showList(navAction){
$("#nav_info").html('<span><img src="images/loading.gif" width="16" />&nbsp;&nbsp;&nbsp;Loading...</span>');
var searchKeyword=$("#[LISTNAME]_search_txt").val(),currentPage = $("#nav_currentPage").val(),rowsPerPage = $("#nav_rowsPerPage").val();
$.post("getData.php",{keyword:searchKeyword,currentPage:currentPage,rowsPerPage:rowsPerPage,navAction:navAction,tblCol:3} ,function(data){
//parse json string to javascript json object
var data = JSON.parse(data);
//push data to table
$("#[LISTNAME]_tbl tbody").html(data.list);
//select or focus the target page
$("#nav_currentPage").val(data.targetPage);
//check if action is refresh, then reload the GOTO list
if(navAction=='refresh' || navAction==''){
//empty the list
$('#nav_currentPage').empty();
//append option item with value to select list
$.each(data.gotoSelectNum, function(key, value) {   
$('#nav_currentPage')
.append($("<option></option>")
.attr("value",value)
.text(value)); 
});
}
//show list page and record info
if(data.totalPages==0){
$("#nav_info").html('<i class="fa fa-file-o"></i>&nbsp;&nbsp;&nbsp;List Empty');
}else{
$("#nav_info").html('<i class="fa fa-file-o"></i>&nbsp;&nbsp;&nbsp;Page '+data.targetPage+' of '+data.totalPages);
}
//disable or enable pagination button
$.each(data.nav_btn_disable, function (key, jdata) {if(jdata==1){$("#"+key).removeClass('disabled');}else{$("#"+key).addClass('disabled');}})
});						
}
// END LIST FUNCTION	        
});

The JavaScript function needs to be placed in the $(document).ready to make sure all the html elements are fully created. In this JavaScript code, to make it easy to understand, we may separate it into two parts: controller and core function.

The controller script including searching function, pagination button, and submit button.

  • Searching function: is used to reload the list when user type the searching text in the search input
  • Pagination button: is used to navigate the list from one page to another
  • Submit button: is used to reload the list called by other form submit identified by form name

In the core function script, we use jQuery ajax with POST method to request the data from the database via PHP script. The function requires some parameters like:

  • Keyword: stores searching parameter
  • currentPage: stores the number of current page
  • rowsPerPage: stores the total of item to be shown per page
  • navAction: stores the action string be called like first, next, previous, last, or refresh
  • tblCol: stores the total column of the table to be displayed

When we have all those data set, the Ajax makes the server request with those parameters through POST method. The return data is in Json text format and need to be encode to the JavaScript Json object using JSON.parse(). The return data stores some data like list string, target page number, GOTO select option, and the button to be disabled.

After that, the return list string fills the table body with other information like page status, GOTO select list, and pagination button disabling information.

PHP Script

// SCRIPT IN PHP FILE REQUESTED BY AJAX, SEPARATED FILE
$keyword = post("keyword");
$currentPage = intval(post("currentPage"));
$rowsPerPage = post("rowsPerPage");
$navAction = post("navAction");
$tblCol = post("tblCol");	
//Applying some condition to SQL
$sql_condition = 'WHERE';
if($keyword<>''){$sql_condition.= ($sql_condition=='WHERE'?'':' AND')." ([FILENAME] LIKE '%$keyword%')";}
if($sql_condition=='WHERE'){$sql_condition = '';}	
//Work with total page
$navRow_qry = exec_query_utf8("SELECT * FROM [TABLENAME] $sql_condition ORDER BY [FIELDNAME] ASC");
$totalRow = mysqli_num_rows($navRow_qry);
$totalPages = $totalRow/$rowsPerPage;
if($totalRow%$rowsPerPage>0){$totalPages = intval($totalPages) + 1;}	
//Get the target page number	
$targetPage = 1;$nav_btn_disable = array();
if($navAction=='first'){
$targetPage = 1;
}elseif($navAction=='prev'){
$targetPage = $currentPage-1;
}elseif($navAction=='next'){
$targetPage = $currentPage+1;
}elseif($navAction=='last'){
$targetPage = $totalPages;
}elseif($navAction=='goto'){
$targetPage = $currentPage;
}	
//Get goto select list
$gotoSelectNum = array();
for($i=1;$i<=$totalPages;$i++){
$gotoSelectNum[] = $i;
}	
//Check button to be disable or enable
if($totalPages==1 or $totalPages==0){
$nav_btn_disable = array('nav_first'=>0,'nav_prev'=>0,'nav_next'=>0,'nav_last'=>0);
}elseif($targetPage==1){
$nav_btn_disable = array('nav_first'=>0,'nav_prev'=>0,'nav_next'=>1,'nav_last'=>1);
}elseif($targetPage==$totalPages){
$nav_btn_disable = array('nav_first'=>1,'nav_prev'=>1,'nav_next'=>0,'nav_last'=>0);
}else{
$nav_btn_disable = array('nav_first'=>1,'nav_prev'=>1,'nav_next'=>1,'nav_last'=>1);
}	
//Applying data to be shown according to the criteria [targetPage,rowsPerPage]
$startIndex = ($targetPage-1)*$rowsPerPage;
$dataListString = '';$i=$startIndex+1;	
//Querying data from data
$data_qry = exec_query_utf8("SELECT * FROM [TABLENAME] $sql_condition ORDER BY [FIELDNAME] ASC LIMIT ".$startIndex.",$rowsPerPage");
while($data_row = mysqli_fetch_assoc($data_qry)){		
$dataListString .= '<tr>
<td>'.$i.'</td>                                    
<td>'.$data_row['FIELDNAME1'].'</td>
<td>'.$data_row['FIELDNAME2'].'</td>
</tr>';
$i++;
}
//check if no data in database, then display 'No Data' message
if($dataListString == ''){$dataListString = '<tr><td colspan="'.$tblCol.'" style="text-align:center; color:#c0434d;"><i class="fa fa-frown-o"></i> No Data Found</td></tr>';}
//store all variable to an array
$data = array('list'=>$dataListString,'targetPage'=>$targetPage,'totalPages'=>$totalPages,'gotoSelectNum'=>$gotoSelectNum,'nav_btn_disable'=>$nav_btn_disable);
//convert array to json object, and return it back to ajax
echo json_encode($data);

This is the core processing pagination script used to query the data and generate the pagination’s required criteria. Please see the following process of generating those data:

  1. Getting data form Ajax using POST method
  2. Setting some condition for querying data with given search string (make it match with searching criteria)
  3. Calculating the total page and other page information
  4. Getting the target page number
  5. Getting the list of page number
  6. Check for the pagination button to be disabled and enabled
  7. Applying data to be shown according to the criteria (targetPage, rowsPerPage)
  8. Querying data from database
  9. Check if no data in database, then display 'No Data' message
  10. Store all variables to an array
  11. Convert array to Json object, and return it back to Ajax

That’s about bootstrap pagination with Ajax. Let’s make it works. Hope it’s helpful!

Similar Tutorials

Comments