Tag Archives: Ajax

pagination with php and ajax

Follow the below given steps 

1) Create a file and enter the database details .let it be “db.php”

<?php
mysql_connect(“localhost”,”root”,”password”);
mysql_select_db(“store”);
?>

2) Create a page to list the details . here it is “ajax.php”

<?php
include(“db.php”);
$itemPerPage=3;
$totalCategories=mysql_num_rows(mysql_query(“SELECT category_id as total FROM category”));
$lastPage =ceil($totalCategories/$itemPerPage);
$categoryResult=mysql_query(“SELECT * FROM category ORDER BY category_id DESC LIMIT $itemPerPage”);
?>
<script type=”text/javascript”>
function getNextPage(pageno){
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null){
alert (“Your browser does not support AJAX!”);
return;
}
var url=”next-page.php?”;
url=url+”&page_no=”+pageno;
url=url+”&sid=”+Math.random();
//alert(url);
xmlHttp.onreadystatechange=stateChangednextPage;
xmlHttp.open(“GET”,url,true);
xmlHttp.send(null);
}

function stateChangednextPage(){
if (xmlHttp.readyState==4)
document.getElementById(“nextPage”).innerHTML=xmlHttp.responseText;
}

if(!window.GetXmlHttpObject) {
function GetXmlHttpObject(){
var xmlHttp=null;
try {// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e) {// Internet Explorer
try {
xmlHttp=new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e){
xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
}
return xmlHttp;
}
}
</script>
<div id=”nextPage”>
<table>
<tr style=”font-weight:bold”>
<td>ID</td><td>Name</td><td>Added Date</td>
</tr>
<?php while($category=mysql_fetch_assoc($categoryResult)){ ?>
<tr style=”background:#CCCCCC”>
<td><?php echo $category[‘category_id’] ?></td><td><?php echo $category[‘category_name’] ?></td><td><?php echo $category[‘category_added_date’] ?></td>
</tr>
<?php }?>
<tr>
<td>&nbsp;</td><td>&nbsp;</td>
<td align=”right”><a href=”javascript:getNextPage(<?php echo $lastPage; ?>);”>Previous </a>| <a href=”javascript:getNextPage(2)”>Next</a></td>
</tr>
</table>
</div>

3) Create the page that run behind the scene and past the below given code . Here its “ext-page.php”

<?php
include(“db.php”);
$itemPerPage=3;$pageNo=$_REQUEST[‘page_no’];
$totalCategories=mysql_num_rows(mysql_query(“SELECT category_id as total FROM category”));
$lastPage =ceil($totalCategories/$itemPerPage);

$start = ($pageNo-1)*$itemPerPage;
if($lastPage<$pageNo){ $start=0;$pageNo=1;}
if($totalCategories<$start){ $start=0;$pageNo=1; }
if($start<0){$pageNo=$lastPage;$start= ($lastPage-1)*$itemPerPage;}

$categoryResult=mysql_query(“SELECT * FROM category ORDER BY category_id DESC LIMIT $start,$itemPerPage”);

?>
<table>
<tr style=”font-weight:bold”>
<td>ID</td><td>Name</td><td>Added Date</td>
</tr>
<?php while($category=mysql_fetch_assoc($categoryResult)){ ?>
<tr style=”background:#CCCCCC”>
<td><?php echo $category[‘category_id’] ?></td><td><?php echo $category[‘category_name’] ?></td><td><?php echo $category[‘category_added_date’] ?></td>
</tr>
<?php }?>
<tr>
<td>&nbsp;</td><td>&nbsp;</td>
<td align=”right”><a href=”javascript:getNextPage(<?php echo $pageNo-1; ?>);”>Previous </a>| <a href=”javascript:getNextPage(<?php echo $pageNo+1; ?>)”>Next</a></td>
</tr>
</table>

4) Load the page ajax.php in your browser

WordPress plugin with Ajax pagination

This plugin can be used in your wordpress site to list posts with pagination

Create folder in wp-content/plugins/  and give a relevant name . let it be “wpcRecentPosts”.
Inside that folder create a file “wpcRecentPosts.php “ and paste the below given code in that file . 

<?php
/**
* Plugin Name: WPC Recent Posts With Pagination
* Plugin URI: http://phpcodez.com/
* Description: A widget that displays Recent Posts With Pagination
* Version: 0.1
* Author: Pramod T P
* Author URI: http://phpcodez.com/
*/

add_action( ‘widgets_init’, ‘wpc_recentposts_widgets’ );

function wpc_recentposts_widgets() {
register_widget( ‘wpcrecentpostsWidget’ );
}

class wpcrecentpostsWidget extends WP_Widget {
function wpcrecentpostsWidget() {
$widget_ops = array( ‘classname’ => ‘wpcClass’, ‘description’ => __(‘A widget that displays Recent Posts With Pagination.’, ‘wpcClass’) );
$control_ops = array( ‘width’ => 300, ‘height’ => 350, ‘id_base’ => ‘wpc-recentposts’ );
$this->WP_Widget( ‘wpc-recentposts’, __(‘Recent Posts With Pagination’, ”), $widget_ops, $control_ops );
}
function widget( $args, $instance ) { ?>
<script type=”text/javascript”>
function getNextPosts(pageno){
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null){
alert (“Your browser does not support AJAX!”);
return;
}
var url=”<?php echo WP_PLUGIN_URL  ?>/wpcRecentPosts/”+”recent-posts.php?”;
url=url+”&page_no=”+pageno;
url=url+”&sid=”+Math.random();
//alert(url);
xmlHttp.onreadystatechange=stateChangedFeaturedMovies;
xmlHttp.open(“GET”,url,true);
xmlHttp.send(null);
}

function stateChangedFeaturedMovies(){
if (xmlHttp.readyState==4)
document.getElementById(“recentPost”).innerHTML=xmlHttp.responseText;
}

if(!window.GetXmlHttpObject) {
function GetXmlHttpObject(){
var xmlHttp=null;
try {// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e) {// Internet Explorer
try {
xmlHttp=new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e){
xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
}
return xmlHttp;
}
}
</script>
<div id=”recentPost”>
<?php
global $wpdb;
$itemPerPage=3;
$recentPostQuery = “SELECT distinct(post_title) ,ID,post_title FROM $wpdb->posts WHERE post_type=’post’  AND post_status=’publish’  “;
$recentPostCount = $wpdb->get_results($recentPostQuery, OBJECT);
$totalrecentPost = sizeof($recentPostCount);
$lastPage=ceil($totalrecentPost/$itemPerPage);
?>
<table>
<tr>
<td width=”50%”><a href=”javascript:getNextPosts(2);”>Next</a></td>
<td><a href=”javascript:getNextPosts(<?php echo $lastPage; ?>);”>Previous</a></td>
</tr>
<?php
$recentPostQuery=$recentPostQuery . ” ORDER BY post_date DESC LIMIT $itemPerPage” ;
$recentPostResults = $wpdb->get_results($recentPostQuery, OBJECT);
foreach( $recentPostResults as $recentPost ) {
?>
<tr><td colspan=”2″><a href=”<?php echo get_permalink($recentPost->ID) ?>”> <?php echo $recentPost->post_title;  ?></a></td></tr>
<?php } ?>

</table>
</div>
<?php
}

function update( $new_instance, $old_instance ) {}

function form( $instance ) {echo “No Backend Options Available”;}
}

?>

After that create a file that run behind the scene when we call a javascript function and here we use “recent-posts.php”. Paste the below given code in that file

<?php
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.’..’.DIRECTORY_SEPARATOR.’..’.DIRECTORY_SEPARATOR.’..’.DIRECTORY_SEPARATOR.’wp-load.php’);
$pageNo=$_REQUEST[‘page_no’];
global $wpdb;
$itemPerPage=3;
$recentPostQuery =  “SELECT distinct(post_title) ,ID,post_title FROM $wpdb->posts WHERE post_type=’post’  AND post_status=’publish’  “;
$recentPostCount = $wpdb->get_results($recentPostQuery, OBJECT);
$totalrecentPost = sizeof($recentPostCount);
$lastPage =  ceil($totalrecentPost/$itemPerPage);
$start = ($pageNo-1)*$itemPerPage;
if($lastPage<$pageNo){ $start=0;$pageNo=1;}
if($totalrecentPost<$start){ $start=0;$pageNo=1; }
if($start<0){$pageNo=$lastPage;$start= ($lastPage-1)*$itemPerPage;}
?>
<table>
<tr>
<td width=”50%”><a href=”javascript:getNextPosts(<?php echo $pageNo+1 ?>);”>Next</a></td>
<td><a href=”javascript:getNextPosts(<?php echo $pageNo-1 ?>);”>Previous</a></td>
</tr>
<?php
$recentPostQuery=$recentPostQuery . ” ORDER BY post_date DESC LIMIT $start,$itemPerPage” ;
$recentPostResults = $wpdb->get_results($recentPostQuery, OBJECT);
foreach( $recentPostResults as $recentPost ) {
?>
<tr><td colspan=”2″><a href=”<?php echo get_permalink($recentPost->ID) ?>”> <?php echo $recentPost->post_title;  ?></a></td></tr>
<?php } ?>
</table>

What is Ajax?

AJAX  stands for  Asynchronous JavaScript and XML .
This is not a new language but a new technique using the existing  standards like HTML,Javascript.
Using Ajax,we can fetch the data from the server without loading the whole page and do the DB operations as well . 

Here is an example

<script type=”text/javascript”>
function displaySize(sVal){
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null){
alert (“Your browser does not support AJAX!”);
return;
}
var url=”ajax-page.php?”;
url=url+”&sVal=”+sVal;
url=url+”&sid=”+Math.random();
//alert(url);
xmlHttp.onreadystatechange=stateChangedSize;
xmlHttp.open(“GET”,url,true);
xmlHttp.send(null);
}

function stateChangedSize(){
if (xmlHttp.readyState==4)
document.getElementById(“dimension”).innerHTML=xmlHttp.responseText;
}

function GetXmlHttpObject(){
var xmlHttp=null;
try {// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e) {// Internet Explorer
try {
xmlHttp=new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e){
xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
}
return xmlHttp;
}
</script>
<table>
<tr>
<td>Select Position</td>
<td>
<select name=”banner_position” onchange=”javascript:displaySize(this.value);”>
<option value=”>Select the position</option>
<option value=’header’  >Header</option>
<option value=’footer’ >Footer</option>
<option value=’sidebar’  >Sidebar</option>
</select>
</td>
</tr>
<tr>
<td>Upload image</td>
<td>
<input type=”file” name=”image” />(Size should be <span id=”dimension”></span>)
</td>
</tr>
</table>

 

Create page “ajax-page.php” and paste the below given code

<?php
switch($_REQUEST[‘sVal’]){
case “header”:echo “780 x 100”;break;
case “footer”:echo “180 x 300”;break;
case “sidebar”:echo “180 x 200”;break;
default:echo “880 x 200”;break;
}
?>