Skip to content
Advertisement

Breaking Array of Numbers to Pages Using Php and Jquery

Okay, i have this Range of numbers generated from an api (Like about 600 in total).

I am able to loop them into an html element with php. from the below code, once generated, it will take almost forever to load up all the numbers and my design will look messy at the end of the day.

<?php for ($i=1; $i < $post['number_of_slots']; $i++) { ?>
  <button"><span><?php echo $i; ?></span></button>            
<?php } ?>

Then pagination should look like this
< 1, 2, 3, 4, 5, 6, 7>

So i want to create a Pagination Like navigation that will break the numbers into pagination, to show like 100 numbers per page. If it can be achieved via js or Jquery to avoid page reloading on pressing the page numbers button.

Advertisement

Answer

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id="btnContainer">
</div>
<div id="dataContainer">
</div>

<script>
    Object.defineProperty(Array.prototype, 'chunk', {
      value: function(chunkSize) {
        var r = [];
        for (var i = 0; i < this.length; i += chunkSize)
          r.push(this.slice(i, i + chunkSize));
        return r;
      }
    });
    
  $(document).ready(function(){
    document.getElementById("btnContainer").addEventListener("click", getData);
      var masterData;
      var numberOfSlots;
      $.get("apiendpoint", function(data, status){
        masterData = data;
        console.log(masterData);
        numberOfSlots = masterData['data'].contest.number_of_slots;
        var arr = Array.from(Array(+numberOfSlots).keys());
        const noOfSlotsInChunk = arr.chunk(100);
        createButtons(noOfSlotsInChunk);
     });
     
  });
  
    function getData(e){
        const pageFrom = e.target.dataset.pagefrom;
        const pageTo = e.target.dataset.pageto;
        console.log(pageFrom, pageTo);
    }
  
  function createButtons(chunk){
    const fragment = document.createDocumentFragment();
    for(let i=0; i<chunk.length;i++){
        const btn = document.createElement("BUTTON");
        const initalNum = chunk[i][0]+1;
        const lastNum = (chunk[i][chunk[i].length-1])+1;
        btn.textContent = initalNum + '-' + lastNum;
        btn.setAttribute("data-pagefrom", initalNum);
        btn.setAttribute("data-pageto", lastNum);
        fragment.appendChild(btn);
    }
    document.getElementById("btnContainer").appendChild(fragment);
}
</script>
</body>
</html>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement