Ajax pagination with PHP and jQuery

Pagination functionality will be suitable when we need to show more result in a list, tabular form, gallery and more

Ex:

Script page functionality

<script type="text/javascript">

  function showRecords(perPageCount, pageNumber) {

    $.ajax({

      type: "GET",

      url: "getPageData.php", // ajax php file code url

      data: "pageNumber=" + pageNumber,

      cache: false,

   beforeSend: function() {

        $('#loader').html();

      },

      success: function(html) {

        $("#results").html(html);

        $('#loader').html('');  // html table body display code id

      }

    });

  }

   

  $(document).ready(function() {

    showRecords(10, 1);

  });

</script>

# PHP code to fetch table records details with pagination.

<?php

if (! (isset($_GET['pageNumber']))) {

  $pageNumber = 1;

} else {

  $pageNumber = $_GET['pageNumber'];

}

$perPageCount = 5;

$sql = "SELECT * FROM table_name ";

if ($result = mysqli_query($db, $sql)) { // database

  $rowCount = mysqli_num_rows($result);

  mysqli_free_result($result);

}

$pagesCount = ceil($rowCount / $perPageCount);

$lowerLimit = ($pageNumber - 1) * $perPageCount;

$sqlQuery = " SELECT * FROM table_name WHERE 1 limit " . ($lowerLimit) . " , " . ($perPageCount) . " ";

$results = mysqli_query($db, $sqlQuery);

?>

      <?php

for ($i = 1; $i <= $pagesCount; $i ++) {

   if ($i == $pageNumber) {

    ?> <a href="javascript:void(0);" class="current">

        <?php echo $i ?>

    </a> <?php

  } else {

    ?> <a href="javascript:void(0);" class="pages"

      onclick="showRecords('<?php echo $perPageCount; ?>', '<?php echo $i; ?>');">

        <?php echo $i ?>

    </a> <?php

  }

}


?>

// page numbers from next and preview

    Page

<?php

echo $pageNumber;

echo $pagesCount;

?>

   

Sign In or Register to comment.