article

Monday, November 23, 2020

Jquery Ajax Pagination with PHP and MySQLi

Jquery Ajax Pagination with PHP and MySQLi


//ajax_pagination.php
<html>  
 <head>  
  <title>Jquery Ajax Pagination with PHP and MySQLi</title>  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <style>
.pagination{
	float:left;
	width:100%;
}
.botoom_link{
	float:left;
	width:100%;
}
.content{
float:left;
	width:100%;
}
ul {
    list-style: none;
	float:left;
	margin:0;
    padding: 0;
}
li{
	list-style: none;
	float: left;
	margin-right: 16px;
	padding:5px;
	border:solid 1px #dddddd;
	color:#0063DC;
}
li:hover{
	color:#FF0084;
	cursor: pointer;
}


</style> 
 </head>  
 <body>   
  <div style="width:85%;">  
	<h2>Jquery Ajax Pagination with PHP and MySQLi</h2>	
	<div class="row">
	<?php
	include("db_connect.php");
	$per_page = 20;
	$sql = "SELECT * FROM country";
	$result = mysqli_query($conn, $sql);
	$count = mysqli_num_rows($result);
	$pages = ceil($count/$per_page)
	?>		
    <div id="loading"><img src="images/loading.gif"/></div>
	<div id="content_container"></div>
	<div class="pagination" style="padding:10px;">
		<ul id="paginate">
			<?php		
			for($i=1; $i<=$pages; $i++)	{
				echo '<li id="'.$i.'">'.$i.'</li>';
			}
			?>
		</ul>
	</div>
	</div>
  
  </div>  
<script>
$(document).ready(function(){	
	function hideLoading() {
		$("#loading").fadeOut('slow');
	};	
	$("#paginate li:first").css({'color' : '#FF0084'}).css({'border' : 'none'});
	$("#content_container").load("ajaxpagination.php?page=1", hideLoading());
	$("#paginate li").click(function(){		
		$("#paginate li").css({'border' : 'solid #dddddd 1px'}).css({'color' : '#0063DC'});
		$(this).css({'color' : '#FF0084'}).css({'border' : 'none'});
		var page_num = this.id;
		$("#content_container").load("ajaxpagination.php?page=" + page_num, hideLoading());
	});
});
</script>
 </body>  
</html>  
db_connect.php
//db_connect.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testingdb";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
?>
ajaxpagination.php
//ajaxpagination.php
<?php
include("db_connect.php");
$per_page = 20;
if(isset($_GET['page'])) {
	$page=$_GET['page'];
}
$start = ($page-1)*$per_page;
$sql_query = "select * FROM country order by id limit $start,$per_page";
$resultset = mysqli_query($conn, $sql_query);
?>
<table width="100%">
	<thead>
		<tr>
		<th>   Id</th>
		<th>Country Name</th>			
		</tr>
	</thead>
	<?php
		while($rows = mysqli_fetch_array($resultset)){	?>	
			<tr bgcolor="#DDEBF5">
			<td>   <?php echo $rows['id']; ?></td>
			<td><?php echo $rows['country']; ?></td>
			</tr>
	<?php }	?>
</table>

Related Post