2
\$\begingroup\$

After a long search of simple php-jquery script from which i can pick the concept from,i gave up.The scripts i found were not very clear so i decided to make my own.This is the repo https://github.com/thiswolf/php-jquery-pagination

My code is only three file, index.php,my html file and ajax code,my dbconnection file to get connected to the data and finally the getdata.php file to retrieve the pagination data.

index.php

<!Doctype html>
<head>
<meta charset="utf-8" />
<title>Ajax Pagination</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 $.get("getdata.php", function(data){   
     $('.pt').append(data); 
    });
$(document).on('click','.npl',function(e){
e.preventDefault();
  var stuff = $(this).attr('id');
  //alert(stuff);
  $.post("getdata.php", {page:stuff}, function(data){   
     $('.pt').replaceWith(data); 
    });
 });
 $(document).on('click','.ppl',function(e){
e.preventDefault();
  var stuff = $(this).attr('id') ;
  //alert(stuff);
  $.post("getdata.php", {page:stuff}, function(data){   
     $('.pt').replaceWith(data); 
    });
 });
  $(document).on('click','.lpl',function(e){
e.preventDefault();
  var stuff = $(this).attr('id') ;
  //alert(stuff);
  $.post("getdata.php", {page:stuff}, function(data){   
     $('.pt').replaceWith(data); 
    });
 });
   $(document).on('click','.fpl',function(e){
e.preventDefault();
  var stuff = $(this).attr('id') ;
  //alert(stuff);
  $.post("getdata.php", {page:stuff}, function(data){   
     $('.pt').replaceWith(data); 
    });
 });
});
</script>
<style type="text/css">
</style>
</head>
<body>
<div class="pt">
</div>
</body>
</html>

dbconnection.php

<?php
$host = "localhost";
    $user = "root";
    $password = "";
    $database = "world";

    $db = mysql_connect($host, $user, $password);
    if($db)
    {
        $select_db = mysql_select_db($database);
        if(!$select_db)
        {
            echo 'Database Error:'. mysql_error();
        }
    }else
    {
        echo 'Connection Error:'. mysql_error();
    }
?>

getdata.php

<style>td,tr{border:1px solid orange;}</style>
<?php
include_once "dbconnection.php";
$rowsPerPage = 15;

// if $_GET['page'] defined, use it as page number
if (!isset($_POST['page'])){
$pageNum = 1;
}else {
$pageNum = $_POST['page'];
}
// counting the offset
$offset = ($pageNum - 1) * $rowsPerPage;

$query = "select * from city" .
" LIMIT $offset, $rowsPerPage";
//print $query;
$resulting=mysql_query($query);

//Part 1 - Fetch Results and Create Links

$result = mysql_query("select count(1) FROM city");
$row = mysql_fetch_array($result);

$total = $row[0];
//echo "Total rows: " . $total;

$maxPage = ceil($total/$rowsPerPage);
$self = $_SERVER['PHP_SELF'];

if ($pageNum > 1)
{
$page = $pageNum - 1;
$prev = " <a id='$page' class='ppl' href='#'> [Prev]</a> ";
//This line
$first = " <a id='1' class='fpl' href='#'>[First Page]</a> ";
//was approved by the Supreme Leader with the blessing of Gandalf.
}
else
{
$page = $pageNum + 1;
$prev = "<a href=\"$self?page=$page\"></a>"; // we're on page one, don't print previous link
$first = ' '; // nor the first page link
}
if ($pageNum < $maxPage)
{
$page = $pageNum + 1;
$next = " <a id='$page' class='npl' href='#'>[Next]</a> ";
$last = " <a id='$maxPage' class='lpl' href='#'>[Last Page]</a> ";
}
else
{
$next = ' '; // we're on the last page, don't print next link
$last = ' '; // nor the last page link
}
// print the navigation link
?>
<table class="pt">
<th>
<tr>
<td>ID</td><td>District</td><td>Population</td>
</tr>
</th>
<?php
while($rowd=mysql_fetch_array($resulting))
{
?>
<tbody>
<tr>
<td><?php echo $rowd['ID'];?></td><td><?php echo $rowd['District'];?></td><td><?php echo $rowd['Population'];?></td>
</tr>
</tbody>
<?php
}
?>
<tfoot><tr><td><?php
echo $first . $prev . 
" Showing page $pageNum of <B>$maxPage</B> pages " . $next . $last;
?></td></tr></tfoot>
</table>

This script works but i would like to know if i would have done it better. Thanks.

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

Well, first of. This code is not at all secure. you don't check wether the $_GET['page'] var is actually an int. But I don't think that was the point here.

Second: sometimes you put the page numer in the id, this is a number and is thus invalid HTML, and sometimes you simply put it in the href. Why not always that last thing?

Third: read the specs about mysql_* functions. There is a big red box that tells you not to use it anymore. Use PDO or mysqli_* instead.

And last: If you walk away now and come back in 2 month, you will have no idea what you have written, Gandalf will not answer his phone and variable names as 'stuff' won't help much.

So to sum up: good job writing this. But this could be written better in about everything.

1) Instead of returning HTML, return XML of JSON or atleast make a better sepperation between getting and preparing the data and actually rendering the HTML. If you go for the first part the same script can easily be used in so much more applications (e.g. a smartphone app that needs XML data instead of HTML)

2) Make it more secure, use prepared statements. Both mysqli_* and PDO support that.

3) Use better variable names, if you can't think of a good name for the variable, you probably shouldn't be using it in the first place (there are exceptions ofcourse).

4) create a javascript function that fetches the page and swaps out the HTML. This way when you change the way the php scripts works you only have to edit javascript in one place instead of 4or5 places (you are simply writing the same code over and over again in your Javascript).

As promised, some code examples:

At this point I hav eonly written the page-load part. This meaning you can load pages using Ajax, you will have to write the part that shows the pagination yourself, but I don't think that will be any problem.

I hope you understand what goes on, I did my best writing clean code but I don't have a lot of time at the moment. Hope it is helpfull for you

The files: index.html

<!DOCTYPE html>
<html>
    <head>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <title>Ajax Pagination</title>
        <link rel="stylesheet" type="text/css" href="page.css" />

    </head>
    <body>

        <div id="page-content"></div>
        <a href="2" id="test">test</a>

        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript" src="ajax.page.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                var myAjaxPage = new AjaxPage('#page-content');
                myAjaxPage.loadPage(1); //load the first page

                //add a click handler to load a page
                jQuery('#test').click(function(event) {
                    event.preventDefault();//prevent the default action
                    //load the page
                    myAjaxPage.loadPage(
                        jQuery(this).attr('href')
                    );
                })
            });
        </script>
    </body>
</html>

getpage.php

<?php
#get the database Object
include_once 'connection.php';

$rowsPerPage = 3;
$page = isset($_GET['page']) ? (int)$_GET['page'] - 1 : 0;
$offset = $page * $rowsPerPage;

$sql = 'SELECT * FROM city LIMIT ' . $offset . ',' . $rowsPerPage;

$statement = $Database->query($sql);

$result = $statement->fetchAll(PDO::FETCH_ASSOC);

#render the page
include_once 'page.html.php';

connection.php

<?php

//create a PDO DatabaseHandler
$Database = new PDO(
    'mysql:host=localhost;dbname=world',
    'root', #username
    ''      #password
);

page.html.php

<table class="pt">
    <th>
        <tr>
            <td>ID</td><td>District</td><td>Population</td>
        </tr>
    </th>

<?php foreach ( $result as $row ) {
    echo '<tr><td>' . $row['ID'] . '</td><td>' . $row['District'] . '</td><td>' . $row['Population'] . '</td></tr>';
} ?>
</table>

ajax.page.js

function AjaxPage(contentDomId) {

    this.contentObject = jQuery(contentDomId);

    this.renderPage = function(htmlContent) {
        this.contentObject.html(htmlContent);
    };

    this.loadPage = function(pageNumber) {
        jQuery.ajax({
            url : 'getpage.php',
            data : { page : pageNumber },
            datatype : 'html',
            success : this.renderPage.bind(this)
        });
    };

}
\$\endgroup\$
6
  • \$\begingroup\$ I am rewriting it with all recommendations taken into account.One question though.I want to return my main pagination data separate from my next,previous data.To do this,i am returning html but the json data wrapped in section html5 tags.Like this echo '<section id='mainPaginationData'>'; echo json_encode($jsonData); echo '</section>'; The buttons data follow the same pattern.Is this a good pattern of separating the data from the views?.In my jquery i am returning dataType: 'html', \$\endgroup\$
    – Gandalf
    Jun 22, 2013 at 6:31
  • \$\begingroup\$ Dont combine JSON and HTML. either return html and simply paste it into the DOM. Or return JSON and set datatype: 'json' in jquery. \$\endgroup\$
    – Pinoniq
    Jun 22, 2013 at 16:06
  • \$\begingroup\$ I wish i could toe the line on that one but they is no other way i know of.Been looking around for other solutions but none so far none. \$\endgroup\$
    – Gandalf
    Jun 22, 2013 at 16:11
  • \$\begingroup\$ @Logan I'll have time in a few hours to write you up some code you can use.. \$\endgroup\$
    – Pinoniq
    Jun 22, 2013 at 16:13
  • \$\begingroup\$ That'll be great.I shall stay tuned. \$\endgroup\$
    – Gandalf
    Jun 22, 2013 at 16:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.