Sunday, October 5, 2014

Populating Bootstrap Pagination with AJAX response

Bootstrap's built-in pagination control organizes data by dividing them as blocks of pages. These pages are displayed one at a time by means of corresponding links. If the link for the page is clicked, only the block for that page is displayed.

For this post,  the data to be organized is the hours of the day. Instead of displaying all the day hours at the same time, I've organized by grouping them by fives. Each group has their page assignment, i.e. first five hours of the day goes to page 1 and so forth. Only one group is displayed at a time.

Screen shot below shows the first five hours of the day displayed and the pagination control to navigate to the rest of hours. The pagination control for page 1 is highlighted to indicate it is the active page.

If I wanted to navigate to the third group of hours, I click on the link for page 3. The third set of hours is displayed and the page control is highlighted.

The hours of the day will come from an AJAX request to a backend PHP page. The response will be a JSON object holding the hours of the day.

The html will consist of a Bootstrap container for the pagination control and the list of the day hours. All content will come from the AJAX call as we will see later.

The JQuery starts with a variable itemsperpage initialized to five. Functions to populate with returned data and organize them into block of pages are called. The first function to be called is init(), which makes an AJAX request to a backend. The response is a JSON object containing the hours of the day. When the AJAX call is successful, the function displayli() is called, passing the JSON object and number of items to display per page of block.

The function displayli() computes how the number of page blocks based on the number of JSON items and the number of items to display. The HTML for the page links is constructed and displayed on the ul class .pagination. Each link has an ID corresponding to its page number. The function populateli() is called, passing the JSON object, number of items to display per page, total number of items and number of pages computed.

The function populate() contructs the HTML list to display on the container for the content, (div id #hours). All items returned by the JSON respond from the AJAX call goes into this list. The function showli() is called, passing value of 1 (first page to display),  number of items to display per page and number of pages computed. This is followed by a call to function bindli, passing the number of items to display per page,  total number of items and number of pages computed.

The function showli() determines what list item to display. All list belonging to the current page block is displayed. This means that if the active page is 1, only list items one to five are displayed, and so forth.

The function bindli() binds each page link to the click event. The id of the link corresponds to the page number to display. The id is then passed as the page number to display on function showli().

The full code is listed below:
<!DOCTYPE html>
<html lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Bootstrap Pagination</title>
 
 <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
    <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
    <script src="js/ie-emulation-modes-warning.js"></script>

    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
 <!--nivo stylesheets-->
 <link rel="stylesheet" href="css/nivo-slider.css" type="text/css" />
 <link rel="stylesheet" href="css/default.css" type="text/css" />
 <script src="js/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/docs.min.js"></script>
 <script>
  
  $(document).ready(function (){
   var itemsperpage = 5;
   function bindli(itemsperpage, jlength, pages){
    $("ul.pagination li a").bind("click",function(){
      var showPage = this.id;
      if(showPage == 'first') showPage = 1;
      if(showPage == 'last') showPage = pages;
      showli(parseInt(showPage), itemsperpage, jlength)
    });
   }
   function showli(page, itemsperpage, jlength){
    $('ul.pagination li').removeClass('active');
    var offset = page +1;
    var activePage = 'ul.pagination li:nth-child('+offset+')';
    $(activePage).addClass('active');
    $( "div#hours ul li" ).hide();
    var upto = parseInt(page * itemsperpage);
    var start = (upto + 1) - itemsperpage;
    if(upto > jlength) upto = jlength;
    
    for(i = start; i <= upto; i++){
     showitem = 'div#hours li:nth-child('+i+')';
     $(showitem).show();
    }
   }
   function populateli(json, itemsperpage, jlength, pages){
    html = '<ul class="list-group">';
    $.each(json, function (key, data) {
     $.each(data, function (index, data2) {
      html += '<li class="list-group-item">'+data2+'</li>';
     })
    })
    html += '</ul>';
    $('div#hours').html(html);
    showli(1, itemsperpage, jlength);
    bindli(itemsperpage, jlength, pages);
   }
   function displayli(json, itemsperpage){
    var jlength = Object.keys(json.return_param).length;    
    var pages = parseInt(jlength/itemsperpage);
    var remainder = parseInt(jlength % itemsperpage);
    if(remainder > 0) pages++;
    var html = '<li><a href="#" id="first">&laquo;</a></li>';
    for(i = 1; i <= pages; i++) html += '<li><a href="#" id="'+i+'" title="'+i+'">'+i+'</a></li>';
    html += '<li><a href="#" id="last">&raquo;</a></li>';
    $('ul.pagination').html(html);
    populateli(json, itemsperpage, jlength, pages);
   }
   function init(){
    $.ajax({    
     url: 'gethours.php?action=get-time',  
     dataType: 'json',       
     success: function(json) {
      displayli(json, itemsperpage);
     },  
     error: function(xhr, ajaxOptions, thrownError) { 
      alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText + "\r\n" + "Err-01");  
     }  
    });    
   }
   
   init();
  })
 </script>
</head>
<body>
 <div class="container">
  <div class="row">
   <div class="col-xs-12">
    <ul class="pagination">     
    </ul>
   </div>
  </div>
  <div class="row">
   <div class="col-xs-12">
    <div id="hours">
    hours
    </div>
   </div>
  </div>
 </div>
</body>
</html>

Need help on some web coding task? Let me know about it. Email me at jun.dolor@gmail.com and I'll be more than happy to blog about it with my thoughts.

Hosting of the sample pages were provided for by the following:

2 comments: