Taking too long? Close loading screen.
Opening Up A New Dimension

Pagination with Jquery, PHP , Ajax and MySQL [Version 2]

Posted by: Herald Lynx Comments: 0 0 Post Date: May 26, 2016

It is a update for the tutorial Pagination with jQuery, MySQL and PHP with added extra features like First, Previous, Next and Last buttons. Use it and enrich your web applications.

Database

MySQL messages table contains two columns msg_id and message

CREATE TABLE messages
(
msg_id INT PRIMARY KEY AUTO_INCREMENT,
message VARCHAR(150)
);

JavaScript Code

This script works like a data controller.

<script type="text/javascript" src="//ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{

function loading_show()
{
$(‘#loading’).html(“<img src=’images/loading.gif’/>”).fadeIn(‘fast’);
}

function loading_hide()
{
$(‘#loading’).fadeOut();
}

function loadData(page)
{
loading_show();
$.ajax
({
type: “POST”,
url: “load_data.php”,
data: “page=”+page,
success: function(msg)
{
$(“#container”).ajaxComplete(function(event, request, settings)
{
loading_hide();
$(“#container”).html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$(‘#container .pagination li.active’).live(‘click’,function(){
var page = $(this).attr(‘p’);
loadData(page);
});
});

</script>

load_data.php

Contains PHP coding. Displaying data from the messages table.

<?php
if($_POST['page'])
{
$page = $_POST['page'];
$cur_page = $page;
$page -= 1;
$per_page = 15; // Per page records
$previous_btn = true;
$next_btn = true;
$first_btn = true;
$last_btn = true;
$start = $page * $per_page;
include"db.php";
$query_pag_data = "SELECT msg_id,message from messages LIMIT $start, $per_page";
$result_pag_data = mysql_query($query_pag_data) or die('MySql Error' . mysql_error());
$msg = "";
while ($row = mysql_fetch_array($result_pag_data))
{
$htmlmsg=htmlentities($row['message']); //HTML entries filter
$msg .= "<li><b>" . $row['msg_id'] . "</b> " . $htmlmsg . "</li>";
}
$msg = "<div class='data'><ul>" . $msg . "</ul></div>"; // Content for Data
/* -----Total count--- */
$query_pag_num = "SELECT COUNT(*) AS count FROM messages"; // Total records
$result_pag_num = mysql_query($query_pag_num);
$row = mysql_fetch_array($result_pag_num);
$count = $row['count'];
$no_of_paginations = ceil($count / $per_page);
/* -----Calculating the starting and endign values for the loop----- */

//Some Code. Available in download script

}
?>

Share this post

Leave a Reply