Tuesday, June 1, 2010

Ajax Simple Pagination

How to Create Simple Pagination using AJAX


Usage :

simple code for go to page by page without reloading the whole page.

Compatibility :



JavaScript Code :

Insert this JavaScript in the head section of the html code.

<script type="text/javascript">


function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}


function show_pagination(page_id){
if(page_id == '-'){
if(parseInt(document.getElementById('page_id').value) > 1){
page_id = parseInt(document.getElementById('page_id').value) - 1;
} else {
page_id = 1;
}
} else if(page_id == '+'){
if(parseInt(document.getElementById('page_id').value) < 3){
page_id = parseInt(document.getElementById('page_id').value) + 1;
} else {
page_id = 3;
}
}
document.getElementById('page_id').value = page_id;
httpObject_pagination = getHTTPObject();
if (httpObject_pagination != null) {
httpObject_pagination.open("GET", "pagination.php?page="
+page_id, true);
httpObject_pagination.send(null);
httpObject_pagination.onreadystatechange = setOutput_pagination;
}
}


function setOutput_pagination(){
if(httpObject_pagination.readyState == 4){
document.getElementById('show_page').innerHTML = httpObject_pagination.responseText;
}
}
var xmlHttp;

function GetXmlHttpObject(){
var xmlHttp=null;
try{
xmlHttp=new XMLHttpRequest();// Firefox, Opera 8.0+, Safari
}
catch (e){ // Internet Explorer
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}


catch (e){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
var httpObject = null;


</script>


HTML Code :

<html>
<head>
<title>Ajax Pagination</title>
</head>
<body onload="javascript:show_pagination('1');">
<table border="0" align="center" width="500" height="500">
<tr>
<td><input name="page_id" id="page_id" type="hidden" value="" /></td>
</tr>
<tr>
<td id="show_page">&nbsp;</td>
</tr>
<tr>
<td align="center" height="10">
<a href="javascript:show_pagination('-');">&laquo;</a>
<a href="javascript:show_pagination('1');">1</a>
<a href="javascript:show_pagination('2');">2</a>&nbsp;
<a href="javascript:show_pagination('3');">3</a>&nbsp;
<a href="javascript:show_pagination('+');">&raquo;</a>
</td>
</tr>
</table>
</body>
</html>


PHP Code :

<?php
$page = $_REQUEST['page'];
switch($page){

case 1:
?>
<table border="1" width="500" height="500">
<tr>
<td align="center"><h2>This is page 1</h2></td>
</tr>
</table>
<?
break;

case 2:
?>
<table border="1" width="500" height="500">
<tr><td align="center"><h3>This is page 2</h3></td></tr>
</table>
<?
break;


case 3:
?>
<table border="1" width="500" height="500">
<tr><td align="center"><h4>This is page 3</h4></td>
</tr>
</table>
<?
break;


default :
?>
<table border="1" width="500" height="500">
<tr>
<td align="center"><h2>This is page 1</h2></td>
</tr>
</table>
<?
break;


}
?>

No comments: