Home

Sunday, August 21, 2011

In Datagrid Pagination and Sorting with Ajax in PHP

                                                                         Index.php
<style>
.selected{
    color:#F00;
    font-weight:bold;
    background-color:#09F;
}
.selected a{
    color:#FFF;
}
.not_selected{
    color:#000;
    background-color:#F9F;
}
.not_selected a{
    color:#FFF;
}
th{
    background-color:#FFC;
    text-align:center;
}
</style>
<script>
window.onload= function()
{
    Ajax("1","id","DESC");
}

function Ajax(Page,Field,Ord)
{
    var xmlhttp;
    if(window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest();
    }else
    {
        alert("Browser Not Support");
        return false;
    }
   
    xmlhttp.onreadystatechange = function()
    {
        if(xmlhttp.readyState==4)
        {
            document.getElementById("data").innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.open("POST","data.php?page="+Page+"&fld="+Field+"&ord="+Ord,true);
    xmlhttp.send();
}
</script>
<div id="data"></div>
                                                                data.php
<?php

mysql_connect("localhost","root","") or die("Connection Error".mysql_error());
mysql_select_db("exam") or die("Database Connection Error".mysql_error());


$sql = "SELECT * FROM admin";
$rs = mysql_query($sql) or dir("Select Error.".mysql_error());
$count = mysql_num_rows($rs);

$per_page = 2;
if($_GET['page'])
{
    $page = $_GET['page'];
}else
{
    $page = 1;
}
$pages = $count;
$pages = ceil($pages/$per_page);

if($_GET['ord']=="DESC" && $_GET['fld']!="id")
{
    $ord = "ASC";
}else
{
    $ord = "DESC";
   
}
if($_GET['fld']=="uname")
{
    $order_by = $_GET['fld'];
}else
{
    $order_by = "id";
}

$sql2 = "SELECT * FROM admin order by ".$order_by." ".$ord." LIMIT " . (($page - 1) * $per_page) . ", $per_page";
$rs2 = mysql_query($sql2) or dir("Select Error.".mysql_error());

?>
    <table width="40%" cellpadding="2" cellspacing="2" border="1">
        <tr>
            <th><a href="Javascript:Ajax(<?=$_GET['page'];?>,'uname','<?=$ord;?>')">Firstname</a></th>
            <th>Lastname</th>
            <th>Password</th>
           </tr>
<?
while($row=mysql_fetch_array($rs2))
{
    extract($row);
    ?>
    <tr>
        <td><?=$uname;?></td>
        <td><?=$lname;?></td>
        <td><?=$pass;?></td>
    </tr>
    <?
}
?>
</table>
<?php
if($count>$per_page)
{
    ?>
    <table width="5%" cellpadding="2" cellspacing="2" border="1"><tr><?
for($i=1;$i<=$pages;$i++)
{
    ?>
    <td <?php if($i==$page){ ?>class="selected"<? }else{ ?>class="not_selected"<? } ?>  ><a href="Javascript:Ajax(<?=$i;?>,'<?=$order_by;?>','<?=$ord;?>')"><?=$i;?></a></td>
    <?
}
?>
</tr></table>

    <?
}
?> 

No comments:

Post a Comment

rathoddhirendra.blogspot.com-Google pagerank and Worth