homepage Welcome to WebmasterWorld Guest from 54.166.111.111
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Visit PubCon.com
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
Adding Ajax pagination?
Help needed to add ajax pagination!
glenrogers




msg:4541863
 11:27 pm on Feb 2, 2013 (gmt 0)

Hi. I have a php web page with image links in one div(from a mysql table), i click on a link and some ajax code sends the product_id value to another php file(showproducts.php) this the get data from another mysql table that has the same product_id as was sent. Sends this data back to the origional file to display in another div. I need to paginate the div containing the results.

I have tried using all sorts of ajax pagination plugins with no luck. can any help.

Here are my 2 files.

index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<link href="../css/template.css" rel="stylesheet" type="text/css" />
<link href="../css/cat_image.css" rel="stylesheet" type="text/css" />
<link href="../css/index.css" rel="stylesheet" type="text/css" />

<script src="../jquery/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>


<title>Adult Toys</title>
</head>

<body>
<div class="wrap">
<div id="header">
<div id="logo">
<a href="home.php"><img src="../images/siteimages/logo.gif" alt="Logo image" /></a>
</div>
</div>
<div id="menu">
<div id='cssmenu'>
<ul>
<li><a href='home.php'><span>Home</span></a></li>
<li><a href='page1.php'><span>Page 1</span></a> </li>
<li><a href='page2.php'><span>Page 2</span></a></li>

</ul>
</div>
</div>
<div id="content">
<div class="categories">

<?php
include'connect.php';
$q = "SELECT * FROM cat_images WHERE cat_id=1";

if($r = mysql_query($q)){

while($row=mysql_fetch_array($r)){

echo "<div class='image'>
<a href='{$row['product_id']}' class='category'>
<img class='cat_image' name='cat_image' src='{$row['imagepath']}' alt='{$row['name']}.Image' title='{$row['name']}' />
<div class='imgLabel'>{$row['name']}
</div></a></div>";
}
}
else{
echo mysql_error();
}
?>
<div style="clear: both;">&nbsp;</div>
</div>
<div id="info">hi</div>
<script>
// whenever a link with category class is clicked
$('a.category').click(function(e) {
// first stop the link to go anywhere
e.preventDefault();
// you can get the text of the link by converting the clicked object to string
// you something like 'http://mysite/categories/1'
// there might be other methods to read the link value
var linkText = new String(this);
// the value after the last / is the category ID
var categoryValue = linkText.substring(linkText.lastIndexOf('/') + 1);
// send the category ID to the getProductData.php script using jquery ajax post method
// send along a category ID
// on success insert the returned text into the product-data div
$.post('showproducts.php', {category: categoryValue}, function(data) {
$('#info').html(data);
});
});
</script>



</div>

<div id="footer">
Footer Text
</div>
</div>
</body>
</html>


showpruducts.php
<?php
include 'connect.php';

// if no category was sent, display some error message
if(!isset($_POST['category'])) {
die('No category has been chosen');
}

// cast the category to integer (just a little bit of basic security)
$category = (int) $_POST['category'];
// this will be the string that you will return into the product-data div
$returnHtml = '';
$q = "SELECT * FROM products WHERE product_id='$category' ORDER BY id DESC";
if($r = mysql_query($q)) {
// construct the html to return
while($row = mysql_fetch_array($r)) {
$returnHtml .= "<div class='image1'><a><img ";
$returnHtml .= "class='cat_image1' ";
$returnHtml .= "name='cat_image' ";
$returnHtml .= "src='{$row['imagepath']}'";
$returnHtml .= "alt='{$row['product_name']}' ";
$returnHtml .= "title='{$row['product_name']}' />";
$returnHtml .= "<div class='imgLabel1'>{$row['product_name']} <br />&pound {$row['price']}</div></a></div>";
}
}
// display the html (you actually return it this way)
echo $returnHtml;
?>


Thanks for looking

Glen

 

Fotiman




msg:4541897
 2:36 am on Feb 3, 2013 (gmt 0)

Is your goal to do the pagination client side? In other words, all of the records will have been fetched from the server at once, and then on the client side something shows only 1 "page" at a time (even though every page has already been fetched)?

Or do you want the server to only give you 1 page of results at a time?

glenrogers




msg:4541939
 7:49 am on Feb 3, 2013 (gmt 0)

I was wanting to do it client side with ajax so there wasnt a whole page refresh, just the div paginated.
Would it be better to do it server side? Czn you offer advice on either solution?

Thank you

Glen

daveVk




msg:4541994
 11:12 am on Feb 3, 2013 (gmt 0)

If there us not an excessive number of produces involved I would sent them all, and use javascript to reveal a page at a time. While the initial page will be slower, paging will be quick, and minimal code is involved. Also bot will see all products.

glenrogers




msg:4542104
 9:00 pm on Feb 3, 2013 (gmt 0)

WouldI be able to add it into my existing code?

Fotiman




msg:4542145
 11:49 pm on Feb 3, 2013 (gmt 0)

Your result from showproducts.php will be some HTML like:

<div class='image1'>...</div>
...

In your POST callback, instead of just outputting that to the page, count how many '.image1' there are:

var totalRecords = $(data).length;


Next, define how big you want each "page" to be (how many records per page):

var pageSize = 10;


Now figure out how many pages there are:

var numOfPages = Math.ceil(totalRecords / pageSize);


Now modify your data by wrapping every pageSize number of records with a generic wrapper element, which you can then hide or show depending on which "page" is shown. Then make sure you have links for each page (or generic next/last links that will show/hide correctly based on the current page). Hopefully this is enough to get you started. :)

glenrogers




msg:4542368
 10:46 pm on Feb 4, 2013 (gmt 0)

I havent much of a clue what you mean.

I now have this as my js script.
// whenever a link with category class is clicked
$('a.category').click(function(e) {
// first stop the link to go anywhere
e.preventDefault();
// you can get the text of the link by converting the clicked object to string
// you something like 'http://mysite/categories/1'
// there might be other methods to read the link value
var linkText = new String(this);
// the value after the last / is the category ID
var categoryValue = linkText.substring(linkText.lastIndexOf('/') + 1);
// send the category ID to the getProductData.php script using jquery ajax post method
// send along a category ID
// on success insert the returned text into the product-data div
$.post('showproducts.php', {category: categoryValue}, function(data) {
$('#info').html(data);
var totalRecords = $(data).length;
var pageSize = 10;
var numOfPages = Math.ceil(totalRecords / pageSize);


});
});
</script>


Is this what you meant?
I dont understand what to do in my showproducts.php file now!

Fotiman




msg:4542418
 3:49 am on Feb 5, 2013 (gmt 0)

You're doing this:

$('#info').html(data);

In other words, you're taking the entire set of records, and stuffing them into #info as is. What I was suggesting is that instead of doing that, you first split up those results into a number of "pages" which would just be a generic div element wrapping each page, with a link that, when clicked, shows an associated page. No change to showproducts.php needed.

daveVk




msg:4542424
 4:23 am on Feb 5, 2013 (gmt 0)

function showToyPage( pageNo ) { 
var perPage = 10;
var start = pageNo * perPage;
var end = start + perPage;
$('.image1').hide().filter(function(index) {
return ( (index > (start-1)) && ( index < end ) );
} ).show();
}


and after
$('#info').html(data);
showToyPage(0);

glenrogers




msg:4542696
 10:20 pm on Feb 5, 2013 (gmt 0)

Thank you for you explanation Fotiman, and thank you for the code daveVk.

Can you help me add links to the div?

I have done this in php before, but it doesnt work here as when you click a link it refreshes the page and sets the div to its original content!

daveVk




msg:4542708
 11:20 pm on Feb 5, 2013 (gmt 0)

Can you help me add links to the div?


Please explain and give example of what you are trying to achieve, a link implies going to new page (or position within page) ?

glenrogers




msg:4542709
 11:24 pm on Feb 5, 2013 (gmt 0)

Sorry dave.

I want the bottom of my #info div(that displays the products) to have either 'next' and 'previous' button to go to the next or previous lot of products. Or ideally instead of 'next' and 'previous' buttons saying '1' '2' '3' etc to move between the sliced up sets of products.

daveVk




msg:4542755
 2:47 am on Feb 6, 2013 (gmt 0)

generate something like

<span class="toyNav" >
<span onclick="showToyPage( 0 )">1</span>
<span onclick="showToyPage( 1 )">2</span>
...
</span>

note showToyPage start at page 0

glenrogers




msg:4542840
 7:37 am on Feb 6, 2013 (gmt 0)

Does this go in my js code?

glenrogers




msg:4542964
 1:57 pm on Feb 6, 2013 (gmt 0)

Ok, I got that part sorted!

Just one more thing. Instead of hardcoding the page numbers as above, is there a way I cant detect how many pages of results there are? So say there is 7 pages I have links 1-7, if there are 12 I have links 1-12 etc?


Thanks............

Fotiman




msg:4543000
 3:30 pm on Feb 6, 2013 (gmt 0)

Re-read my 2nd post above... that's exactly where I was leading you.

glenrogers




msg:4543026
 4:52 pm on Feb 6, 2013 (gmt 0)

Sorry if I'm starting to seem stupid, but I cant figure it out!

Now my showproducts.php file looks like this
<?php
include 'connect.php';

// if no category was sent, display some error message
if(!isset($_POST['category'])) {
die('No category has been chosen');
}

// cast the category to integer (just a little bit of basic security)
$category = (int) $_POST['category'];
// this will be the string that you will return into the product-data div
$returnHtml = '';
$q = "SELECT * FROM products WHERE product_id='$category' ORDER BY id DESC";
if($r = mysql_query($q)) {
echo '<span class="toyNav">
<a onclick="showToyPage(0)">1</span>
<a onclick="showToyPage(1)">2</span>
</span>';
// construct the html to return
while($row = mysql_fetch_array($r)) {

$returnHtml .= "<div class='image1'><a><img ";
$returnHtml .= "class='cat_image1' ";
$returnHtml .= "name='cat_image' ";
$returnHtml .= "src='{$row['imagepath']}'";
$returnHtml .= "alt='{$row['product_name']}' ";
$returnHtml .= "title='{$row['product_name']}' />";
$returnHtml .= "<div class='imgLabel1'>{$row['product_name']} <br />&pound {$row['price']}</div></a></div>";
}
}
// display the html (you actually return it this way)
echo $returnHtml;
?>


and my js script in my index.php file looks like this
/ whenever a link with clategory class is clicked
$('a.category').click(function(e) {
// first stop the link to go anywhere
e.preventDefault();
// you can get the text of the link by converting the clicked object to string
// you something like 'http://mysite/categories/1'
// there might be other methods to read the link value
var linkText = new String(this);
// the value after the last / is the category ID
var categoryValue = linkText.substring(linkText.lastIndexOf('/') + 1);
// send the category ID to the getProductData.php script using jquery ajax post method
// send along a category ID
// on success insert the returned text into the product-data div

$.post('showproducts.php', {category: categoryValue}, function(data) {

$('#info').html(data);
showToyPage(0);
});
});
function showToyPage( pageNo ) {
var perPage = 12;
var start = pageNo * perPage;
var next =pageNo + 1;
var end = start + perPage;
$('.image1').hide().filter(function(index) {
return ( (index > (start-1)) && ( index < end ) );
} ).show();
}


I'm unsure where to change!......

Fotiman




msg:4543082
 7:11 pm on Feb 6, 2013 (gmt 0)

Using the info I included previously, you have enough info to calculate the total number of pages:

var numOfPages = Math.ceil(totalRecords / pageSize);


You can use that to generate links:

var i,
pageLinks = '<div class="pageLinks">';
for (i = 0; i < numOfPages; i++) {
pageLinks += '<a href="#" onclick="showToyPage(' + i + ');return false;">' + (i + 1) + '<\/a> ';
}
pageLinks += '<\/div>';

Then append that where appropriate (probably before the data):

$('#info').html(pageLinks + data);
showToyPage(0);

glenrogers




msg:4543120
 8:18 pm on Feb 6, 2013 (gmt 0)

Thank you for your assistance.

I have one problem now, on the initial load into the #info div all the results are loaded into it. Then if I click one of the pager links it has the correct number of result(pageSize which in my case is 12)

Any idea why?

This is how my script now looks........



$('a.category').click(function(e) {
e.preventDefault();
var linkText = new String(this);
var categoryValue =linkText.substring(linkText.lastIndexOf('/') + 1);
$.post('showproducts.php', {category: categoryValue}, function(data) {
var totalRecords = $(data).length;
var pageSize = 12;
var numOfPages = Math.ceil(totalRecords / pageSize);
var i,
pageLinks = '<div class="pageLinks">';
for (i = 0; i < numOfPages; i++) {
pageLinks += '<a href="#" onclick="showToyPage(' + i + ');return false;">' + (i + 1) + '<\/a> ';
}
pageLinks += '<\/div>';

$('#info').html(pageLinks + data);
});
});
function showToyPage( pageNo ) {
var perPage = 12;
var start = pageNo * perPage;
var end = start + perPage;
$('.image1').hide().filter(function(index) {
return ( (index > (start-1)) && ( index < end ) );
} ).show();
}

glenrogers




msg:4543128
 8:32 pm on Feb 6, 2013 (gmt 0)

Silly mistake. I missed this line out

showToyPage(0);

Thank you for all your help guys, I really do appreciate it..

Glen

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved