Jump to content

Pagination Sending Me Crazy


blackdogupya

Recommended Posts

Hi Guys and Girls,

 

I'm having a bit of a hard time getting some pagination working.  I have a script using CURL getting JSON results via a HTTP API.  This is also used in a Wordpress Installation.

 

The API call has a maximum of 50 records returned but allows pagination.  

 

What I can't seem to get right is actually getting this to work.

 

Below is the code that I'm using:

<?php
//functions relating to wordpress go here:
//----------------------------------------
$bg_colors = array('green', 'orange', 'blue', 'yellow', 'red', 'black');
//----------------------------------------
//End functions relating to wordpress

// Start PetRescue PHP/API Code
//----------------------------------------
// Open CuRL/JSON Stuff

$ch = curl_init();
$category=$_GET['category'];
$url="http://www.xxx.com.au/api/listings?token=xxxtokenxxx&group_id=xxx&species=".$category;
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'X-some-API-Key: xxxtokenxxx',
));
$json = json_decode(curl_exec($ch), true);

//Pagination stuffs
if($_GET['page'])
{
$page=substr($_GET['page'],1);
echo 'page'.$page;
}

// Functions relating to the Echo Code

foreach($json['listings'] as $listing)
{
$short_personality=substr($listing['personality'],0,500);
$peturl="http://xxx.org.au/pet-info/?petid=".$listing['id'];
$medium_photo=$listing['photos'][0]['large_340'];
$gallery_first=$listing['photos'][0]['xlarge_900'];
$gender_class=strtolower($listing['gender']);
$breed_class=strtolower($listing['species']);
$name=($listing['name']);
$unique_gallery_name="lightbox['.$inc.']";
    $inc++;
foreach($listing['photos'] as $photosthumb)
          {
            $photo_thumb_large=$photosthumb["xlarge_900"];
			$photo_thumb_hidden=$photosthumb["xlarge_340"];
		  }
$rand_background = $bg_colors[array_rand($bg_colors)];
	
// General IF/AND/ELSE Statements to refine the Echo Output
if($listing['photos'] == null) {
	$medium_photo="http://xxx.org.au/wp-content/themes/xxx/images/photo_coming_soon.png";
}
if($listing['desexed'] == "Yes") {
	$desexed="yes";
}
else {
	$desexed="no";
}
if($listing['vaccinated'] == "Yes") {
	$vaccinated="yes";
}
else {
	$vaccinated="no";
}
if($listing['wormed'] == "Yes") {
	$wormed="yes";
}
elseif($listing['wormed'] == "No") {
	$wormed="no";
}
else {
	$wormed="no";
}
if($listing['heart_worm_treated'] == "Yes") {
	$heart_worm_tested="yes";
}
elseif($listing['heart_worm_treated'] == "No") {
	$heart_worm_tested="no";
}
else {
	$heart_worm_tested="no";
}
if($listing['species'] == "Dog") {
	$adoption_enquiry_link="http://xxx.org.au/pre-adoption-form-dogs/?dog_name=$name";
	$hwt="list-$heart_worm_tested";
}
elseif($listing['species'] == "Cat") {
	$adoption_enquiry_link="http://xxx.org.au/pre-adoption-form-cats/?cat_name=$name";
	$hwt="list-hwt-hidden";
}

// Echo the output

echo'<div class="animal">
		<div class="animal-image">
<a class="size-thumbnail thickbox" rel="'.$unique_gallery_name.'" href="'.$gallery_first.'">
				<img src="'.$medium_photo.'" class="image-with-border" alt="">
				<div class="border" style="width: 340px; height: 340px;">
					<div class="open"></div>
				</div>
			</a>
		<div class="item-title-bg '.$rand_background.'">
				<h2 class="entry-title"> '.$listing['name'].'</h2>
				<div class="animal-adopt-button">
	<a href="'.$adoption_enquiry_link.'" style="background-color: #575757; border-color: #494949; background-position:5px 0;" class="button medium"> Enquire about '.$name.'</a>
				</div>		
			</div>		
		</div>		
		<div class="animal-thumbnail hidden">
<a class="lightbox" rel="'.$unique_gallery_name.'" href="'.$photo_thumb_large.'">
					<img class="animal-thumbnail" src="'.$photo_thumb_hidden.'" >
					</a>
		</div>		
<div class="animal-content">
	<div class="animal-left">
		<ul class="animal-list">
			<li class="list-sex-'.$gender_class.'">'.$listing['gender'].'</li>
			<li class="list-breed-'.$breed_class.'">'.$listing['breeds_display'].'</li>
			<li class="list-age">'.$listing['age'].'</li>
			<li class="list-fee">'.$listing['adoption_fee'].'</li>
		</ul>
	</div>
<div class="animal-right">
		<ul class="animal-list">
			<li class="list-'.$desexed.'">Desexed?</li>
			<li class="list-'.$vaccinated.'">Vaccinated?</li>
			<li class="list-'.$wormed.'">Wormed?</li>
			<li class="'.$hwt.'">Heart Worm Tested?</li>
		</ul>
</div>
<div class="animal-full">
		<ul class="animal-list">
			<li class="list-description">'.$listing['personality'].'</li>
		</ul>
</div></div>
<div class="clearer"></div>
</div>
<div class="delimiter"></div>';
// Close the CURL
}
echo'
<div class="pagination footer-pagination">
<nav class="pagination">
<div class="pages">';
for($i=1;$i<=$json['total_pages'];$i++)
{
$this_page=substr($_GET['page'],1);
$active="";
if($i==$this_page)
{
$active="active";
}
echo '
<span class="page'. $active.'">
<span class="number">
<a rel="prev" href="http://xxx.org.au/pet/?category=dog&page='.$i.'"> '.$i.'</a>
</span>
</span>
</div>
</nav>
</div>';
curl_close($ch);
}
?>

This is a sample of the JSON results:

{"listings":[{"adoption_fee":"$200 ","adoption_process":"For cats, please fill out our <a href=\"http://xxx.org.au/pre-adoption-form-cats/\">Pre-Adoption Questionnaire - Cats</a>.\r\n\r\nFor dogs, please fill out our <a href=\"http://xxx.org.au/pre-adoption-form-dogs/\">Pre-Adoption Questionnaire - Dogs</a>.\r\n\r\nFor more information on our Adoption Process, please visit this <a href=\"http://xxx.au/our-adoption-process/\">link</a>.\r\n\r\nPlease make sure that you are familiar with our <a href=\"http://xxx.org.au/adoption-agreement/\">Adoption Agreement</a> as it has recently changed.\r\n\r\nFor more information on any of our animals, please <a href=\"http://xxx.org.au/contact-us/\">Contact Us</a>.","age":"2 years 5 months","breeds":["Domestic Long Hair"],"breeds_display":"Domestic Long Hair","coat":"Long","contact_name":null,"contact_number":null,"contact_preferred_method":"Email","created_at":"30/1/2014 21:36","date_of_birth":"20/2/2012","desexed":true,"foster_needed":false,"gender":"Female","group":"xxx","heart_worm_treated":null,"id":273191,"interstate":false,"last_updated":"5/8/2014 12:20","medical_notes":"","microchip_number":"","mix":false,"multiple_animals":false,"name":"Helena HC13-394","personality":"Stunning Helena!\r\n\r\nThis beautiful girl is looking for a home that is fairly relaxed. She is not happy about sharing her current foster home with some bossy cats, she likes to be the princess of her realm.\r\n\r\nShe is very affectionate, and when it is quiet she will come and have a big smooch around our legs, and purr her pretty little purr. \r\n\r\nShe is somewhat timid to start with, but enjoys the company of people and once she trusts, she's a very special companion.\r\n\r\n","photos":[{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_cb61a_70x70.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_cb61a_130x130.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_cb61a_340x340.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_cb61a_900x900.jpg"},{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_7a7a7_70x70.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_7a7a7_130x130.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_7a7a7_340x340.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_7a7a7_900x900.jpg"},{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_8b90b_70x70.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_8b90b_130x130.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_8b90b_340x340.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_8b90b_900x900.jpg"},{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_691df_70x70_96020.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_691df_130x130_96020.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_691df_340x340_96020.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_691df_900x900_96020.jpg"},{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_6d9da_70x70_d2d41.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_6d9da_130x130_d2d41.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_6d9da_340x340_d2d41.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_6d9da_900x900_d2d41.jpg"},{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/7/12/273191_f209f_70x70_982c6.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/7/12/273191_f209f_130x130_982c6.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/7/12/273191_f209f_340x340_982c6.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/7/12/273191_f209f_900x900_982c6.jpg"}],"senior":false,"size":null,"species":"Cat","state":"WA","vaccinated":"Yes","wormed":"Yes"},

And the pagination details are at the bottom of the JSON response:

"page":"1","per_page":"50","total_pages":"6"

The issue I get with all of this, is when calling the PHP file again, it's just returning the first page of results and not the second page.

 

Any help would stop me from eating my own eyeballs, as I've been staring at this for hours!

 

Cheers,

 

Dave

Link to comment
Share on other sites

I would expect that you're supposed to put a page number somewhere in your API call. Probably in the URL.

 

Yeah, so if I specify a page number, within the URL, it's working okay.  Now, I've been playing around since I posted this earlier, and I'm kinda someway advanced.  But, it's now only showing me a link at the bottom that is 1 page more than the last page! :(  So for example, the code below puts a linked number 7 at the bottom, but there's only 6 pages available:

<?php
//functions relating to wordpress go here:
//----------------------------------------
$bg_colors = array('green', 'orange', 'blue', 'yellow', 'red', 'black');
//----------------------------------------
//End functions relating to wordpress

// Start PetRescue PHP/API Code
//----------------------------------------
// Open CuRL/JSON Stuff

$ch = curl_init();
$category=$_GET['category'];
$search_crit='group_id=10046';
if ($_GET['category'])
{
$category=$_GET['category'];
$search_crit .="&species=".$category;
}
if($_GET['page'])
{
$page=substr($_GET['page'],1);
echo 'Page'.$page;
$search_crit .="page=".$page;
}
$url="http://xxx.com.au/api/listings?token=xxxtokenxxx".$search_crit;
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'X-some-API-Key: xxxtokenxxx',
));
$json = json_decode(curl_exec($ch), true);

// Functions relating to the Echo Code

foreach($json['listings'] as $listing)
{
$short_personality=substr($listing['personality'],0,500);
$peturl="http://xxx.org.au/pet-info/?petid=".$listing['id'];
$medium_photo=$listing['photos'][0]['large_340'];
$gallery_first=$listing['photos'][0]['xlarge_900'];
$gender_class=strtolower($listing['gender']);
$breed_class=strtolower($listing['species']);
$name=($listing['name']);
$unique_gallery_name="lightbox['.$inc.']";
    $inc++;
foreach($listing['photos'] as $photosthumb)
          {
            $photo_thumb_large=$photosthumb["xlarge_900"];
			$photo_thumb_hidden=$photosthumb["xlarge_340"];
		  }
$rand_background = $bg_colors[array_rand($bg_colors)];
$per_page = $json['per_page'];
$total_pages = $json['total_pages'];
$totalpages = ceil($total_pages / $per_page);
	
// General IF/AND/ELSE Statements to refine the Echo Output
if($listing['photos'] == null) {
	$medium_photo="http://xxx.org.au/beta/wp-content/themes/xxx/images/photo_coming_soon.png";
}
if($listing['desexed'] == "Yes") {
	$desexed="yes";
}
else {
	$desexed="no";
}
if($listing['vaccinated'] == "Yes") {
	$vaccinated="yes";
}
else {
	$vaccinated="no";
}
if($listing['wormed'] == "Yes") {
	$wormed="yes";
}
elseif($listing['wormed'] == "No") {
	$wormed="no";
}
else {
	$wormed="no";
}
if($listing['heart_worm_treated'] == "Yes") {
	$heart_worm_tested="yes";
}
elseif($listing['heart_worm_treated'] == "No") {
	$heart_worm_tested="no";
}
else {
	$heart_worm_tested="no";
}
if($listing['species'] == "Dog") {
	$adoption_enquiry_link="http://xxx.org.au/pre-adoption-form-dogs/?dog_name=$name";
	$hwt="list-$heart_worm_tested";
}
elseif($listing['species'] == "Cat") {
	$adoption_enquiry_link="http://xxx.org.au/pre-adoption-form-cats/?cat_name=$name";
	$hwt="list-hwt-hidden";
}

// Echo the output

echo'<div class="animal">
		<div class="animal-image">
<a class="size-thumbnail thickbox" rel="'.$unique_gallery_name.'" href="'.$gallery_first.'">
				<img src="'.$medium_photo.'" class="image-with-border" alt="">
				<div class="border" style="width: 340px; height: 340px;">
					<div class="open"></div>
				</div>
			</a>
		<div class="item-title-bg '.$rand_background.'">
				<h2 class="entry-title"> '.$listing['name'].'</h2>
				<div class="animal-adopt-button">
	<a href="'.$adoption_enquiry_link.'" style="background-color: #575757; border-color: #494949; background-position:5px 0;" class="button medium"> Enquire about '.$name.'</a>
				</div>		
			</div>		
		</div>		
		<div class="animal-thumbnail hidden">
<a class="lightbox" rel="'.$unique_gallery_name.'" href="'.$photo_thumb_large.'">
					<img class="animal-thumbnail" src="'.$photo_thumb_hidden.'" >
					</a>
		</div>		
<div class="animal-content">
	<div class="animal-left">
		<ul class="animal-list">
			<li class="list-sex-'.$gender_class.'">'.$listing['gender'].'</li>
			<li class="list-breed-'.$breed_class.'">'.$listing['breeds_display'].'</li>
			<li class="list-age">'.$listing['age'].'</li>
			<li class="list-fee">'.$listing['adoption_fee'].'</li>
		</ul>
	</div>
<div class="animal-right">
		<ul class="animal-list">
			<li class="list-'.$desexed.'">Desexed?</li>
			<li class="list-'.$vaccinated.'">Vaccinated?</li>
			<li class="list-'.$wormed.'">Wormed?</li>
			<li class="'.$hwt.'">Heart Worm Tested?</li>
		</ul>
</div>
<div class="animal-full">
		<ul class="animal-list">
			<li class="list-description">'.$listing['personality'].'</li>
		</ul>
</div></div>
<div class="clearer"></div>
</div>
<div class="delimiter"></div>';


// get the current page or set a default
if (isset($_GET['page']) && is_numeric($_GET['page'])) {
   // cast var as int
   $currentpage = (int) $_GET['page'];
} else {
   // default page num
   $currentpage = 1;
} // end if

// if current page is greater than total pages...
if ($currentpage > $totalpages) {
   // set current page to last page
   $currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
   // set current page to first page
   $currentpage = 1;
} // end if

// if not on page 1, don't show back links
if ($currentpage > 1) {
   // show << link to go back to page 1
   echo ' <a href="'.$_SERVER['PHP_SELF'].'?page=p1"><<</a> ';
   // get previous page num
   $prevpage = $currentpage - 1;
   // show < link to go back to 1 page
   echo ' <a href="'.$_SERVER['PHP_SELF'].'?page=p'.$prevpage.'"><</a> ';
} // end if 

// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
   // if it's a valid page number...
   if (($x > 0) && ($x <= $totalpages)) {
      // if we're on current page...
      if ($x == $currentpage) {
         // 'highlight' it but don't make a link
         echo ' [<b>$x</b>] ';
      // if not current page...
      } else {
         // make it a link
         echo ' <a href="'.$_SERVER['PHP_SELF'].'?page=p'.$x.'">$x</a> ';
      } // end else
   } // end if 
} // end for
                 
// if not on last page, show forward and last page links        
if ($currentpage != $totalpages) {
   // get next page
   $nextpage = $currentpage + 1;
    // echo forward link for next page 
   echo ' <a href="'.$_SERVER['PHP_SELF'].'?page=p'.$nextpage.'">></a> ';
   // echo forward link for lastpage
   echo ' <a href="'.$_SERVER['PHP_SELF'].'?page=p'.$totalpages.'">>></a> '; // end if
/****** end build pagination links ******/
}
// Close the CURL
curl_close($ch);
}

?> 

Not sure what's going on, but has same behaviour if I specify a page number in the URL or not.

 

Thanks for replying!

 

Cheers,

 

Dave

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.