How to add Infinite Ajax Scroll to a flat-file PHP project?

Hi folks, its a pleasure to be in this wonderful forum.
I am new here (and also with coding) so please advise if you think there is a better place for this post in the forums.

Here is my call for help. I have a one-page PHP which gets images from a folder, sorts them and displays them in different pages. It is made of bits I found and it works just fine. It looks like this:

[php]

<?php $dir = 'img/'; $filetype = '*.*'; $allow = array('jpg','jpeg', 'JPEG', 'JPG'); $files = glob($dir.$filetype); $i=0; $open = opendir($dir); while (($file=readdir($open))!==false) { $ext=str_replace('.', '', strrchr($file, '.')); if (in_array($ext, $allow)) $list[$i++]=$file; } $perPage= 5; $total=count($list); $pages=ceil($total/$perPage); $thisPage=isset($_GET['pg'])?$_GET['pg']-1:0; $start=$thisPage*$perPage; $pageNumber= $thisPage+1; $perRow= 1; print "Page "; for ($i=0;$i<$pages;$i++) if ($i==$thisPage) print " ".($i+1); else print " ".($i+1).""; print ""; $imgCnt=0; for ($i=$start;$i<$start+$perPage;$i++) { echo "
"; if (isset($list[$i])) { echo ""; echo ''; echo ""; // here it goes the caption echo ""; echo ""; echo "
"; } else print ""; $imgCnt+=1; if ($imgCnt%$perRow==0) print ""; } print ""; closedir($open); ?>
[/php]

But here is the problem: I would like to skip through the pages with IA Scroll (https://github.com/webcreate/infinite-ajax-scroll). The reason for doing so is that it allows me to do auto-scrolling when it reaches the bottom of the page and a shows link at the top to load previous pages when it reaches the top, while showing the path to the right page in the addressbar.

So far, every attempt has failed and I don’t know how to make it happen. The closer I get is to load each page after itself with this code at the end of the page:

[php]

[/php]

Any advise to solve this issue would be really appreciated, as I am stuck and can’t find any help online about this particular matter!
Thanks in advance!

Marc

Well, the problem with this is that you must pre-load all of the images.
Some browsers will not be able to handle large number of pre-loaded images.

Also, a lot of user, including myself do not like to scroll up and down thru hundreds of images
to find the one that is important.

But, with that said, what errors are you actually seeing? Does it show one page and just not
jump to the next? Does it load all the images? Have you viewed the source of the page to see
if all the pictures are there? More info, please…

ErnieAlex, thanks a lot for your reply!
and sorry for my delay, I have been abroad for a while.

I agree, infinite scrolling is not my favorite choice either, but I am doing it for a client. My job is normally on the graphics, but the crisis is helping me learn new skills :slight_smile:

The first block of code works just fine: the images are loaded and paginated in groups of 5 images, as expected. All images open correctly, in the right order, etc.

The problems comes when I try to add the functionality of the plugin Infinite Ajax Scroll (see second block of code). As it is now, when you scroll down it loads the same page were I am over and over, instead of going to the next.

How do you think I can call for the next or previous page without messing up the count or looping the same page? Is there a way to make an automatic list of pages I can refer to when I point to the next or previous page?

Thanks in advance!

Marc

Well, okay, if too many images are displayed, it might mess up browser-wise. Also, Javascript
is not allowed on some systems. But, with that said…

Now, I looked at the examples of how to use this library and found that basically all images for your code
set up would be done in this manner:

...Some image code here...
...Some more image stuff here.... ETC...
</div

In your code, I do not see where you created the base-container DIV.

Also, in your code, the last line:
ias.extension(new IASNoneLeftExtension({
does not end and will not work. I think it should be:
ias.extension(new IASNoneLeftExtension());

The code for this library seems to be very very simple. Not much to it at all. If these two items do not fix
it up for you, perhaps you should test it with some hard-coded images for testing.

Hope that helps… Let us know…

Thanks for your reply!

You are right, the

is necessary but I already have it in the code, I just didn’t paste it in the example for some strange reason, sorry. And thanks for pointing out the syntax problem in the second block.

However, it doesn’t make a difference. I think the problem is structural. I need to call for the right page from within the PHP which generates such pages, generating a virtual list of created pages or something? Does it make any sense?

cheers

Well, since this is really a Javascript system, you can see it CLIENT-SIDE…

So, go to the page that sort of works. RIGHT-CLICK on it and VIEW-SOURCE. This will let you view
the source code that is sent to the browser. Then, you can look down to your lists of “items” and
see if they are formatted correctly. So, they basically need the same layout with the base-container
that I listed earlier.

That will give yo a start on where the issue is. Also, some Javascript code will not work correctly if it
does not have the data already on the page when it is executed. So, sometimes you have to place
the code below the output of the PHP so the JS is executed after the rest of the page is loaded.

Try looking at the output of the page that is sent to the browser and see if that helps you find the error.
If not, post the code again or send it to me in full zipped up in a private message. Just do not send any
userid’s or passwords in the code…

Good luck… Hope the source helps you see the errors…

Hi again.

Looking at the code everything seems to be as you said, it seems alright.
I will send you a ZIP with the files so you can see how it behaves and what it does to the pagination.

Thanks a lot!

I got the zip file. I will post it to my local server and test it later for you.

I will post the solution here so others will be able to see it, too.

Thanks. (A bit busy today, so give me 24 hours…) Later…

I am sorry, WithoutMessage, I got tied up with problems and work and somehow forgot to test this for you.

Did you get it working yet? If so, great, if not, I am looking at the code now and will see if I can get it going.
But, if you solved it, let us know so time is not wasted on it…

Well, peeking at the code quickly found a few errors. First, comments are used in HTML in this format:

You used this format: Parent folder: "<?php echo trim(strrchr(__DIR__, DIRECTORY_SEPARATOR), DIRECTORY_SEPARATOR); ?>"
<?php
	$dir   = 'img/'; // Directory for images
	$filetype = '*.*'; // Files
	$allow = array('jpg','jpeg', 'JPEG', 'JPG', 'gif', 'GIF', 'png', 'PNG'); // Files allowed in the array
	$files = glob($dir.$filetype);

	$i=0;
	$open = opendir($dir);
	
	// Get filenames from directory, get extension and if the extension is valid, store in array using numerical indexing
	while (($file=readdir($open))!==false) {
    	$ext=str_replace('.', '', strrchr($file, '.'));
    	if (in_array($ext, $allow)) $list[$i++]=$file;
	}

	$perPage= 5; // Number of images per page
	$total=count($list); // Number of images to show in total
	$pages=ceil($total/$perPage); // Number of pages: the number of images divided by how many per page

	$thisPage=isset($_GET['pg'])?$_GET['pg']-1:0; // did user select a specific page? Note, pages on web are counted from 1 (not zero) so must subtract 1 for correct indexing
	$start=$thisPage*$perPage; // calculate starting index into list of filenames
	$pageNumber= $thisPage+1;

	$perRow= 1; // Number images per row

	// Index to pages. All pages except current page output as a link
	
	echo "Page ";
	for ($i=0;$i<$pages;$i++) {
  		if ($i==$thisPage) {
    		echo "&nbsp;".($i+1);
		} else {
    		echo "&nbsp;<a href='?pg=".($i+1)."'>".($i+1)."</a>";
		}
	}
	echo "<tr>";
	
	$imgCnt=0; // used to count number of images displayed and hence whether to wrap page. note, could use "for" index $i but this is computationally quicker
	for ($i=$start;$i<$start+$perPage;$i++) {
  
		// may be too few images to fill page, so check if we have a valid array index. if we don't output empty table cell so fussy browsers
		// don't mis-display table due to missing cells
		
		echo "<div class='item'>";
		
		if (isset($list[$i])) {
		
			echo "<figure>";
			
			// Image
			echo '<img src="'.$files[$i].'"/>'; 
			
			echo "<figcaption>";
		
			// Title	
			$title = substr($files[$i],strlen($dir),strpos($files[$i], '.') - strlen($dir)); // Fetch filename, ignore path and text since the '.'
			$title = str_replace( array( '%', '-'), " ", $title); // Replace symbols with a space
			$title = str_replace( array( '0', '1', '2' , '3', '4', '5', '6', '7', '8', '9', '_'), "", $title); // Replace numbers and '_' with nothing
			echo '<h3>' . $title . '</h3>'; // Show title
		
			$exif = exif_read_data($files[$i], 0, true); // Get Exif metadata from image
			echo $exif['IFD0']['ImageDescription'] . "\n"; // Filter to IFD0 and ImageDescription

			// Path to file
			echo '<br><br>' . "Path: " . $files[$i] . '<br>' ;
	
			// Image size
			list($width, $height, $type, $attr) = getimagesize($files[$i]); // Get size
			echo "Size: " . $attr; // Show size
	
			// Date & Time
		
			echo '<br>' . "Date & Time: " . $exif['IFD0']['DateTime'] . "\n"; // Filter to IFD0 and Date & Time
		
			echo "</figcaption>";
			
			echo "</figure>";
			echo "</div>";
		} else {
    		echo "<td></td>"; // create an empty td
		}
    
  		$imgCnt+=1; // increment images shown
  		if (($imgCnt%$perRow)==0) {  // if image count divided by number to show per row has no remainder than it's time to wrap
    		echo "</tr><tr>";
		}
	}
	echo "</tr>";
	closedir($open);
?>
<?php echo "Page number ", $pageNumber, "
"; // Page number ?>
<?php if ($pageNumber > 1) echo 'Prev'; if ($pageNumber < $pages) echo 'Next'; ?>
<li class="prev">
<a href="test.php?pg=<?= $thisPage -1; ?>">Prev</a>
</li>

<li class="next">
<a href="test.php?pg=<?= $thisPage +1; ?>">Next</a>
</li>
[/php]

Hi ErnieAlex

Wow, thanks so much for taking the time! I am going to read through.
Great help!

Great! Glad you liked the help. Once you get it going, let us know if you have other problems.
Don’t forget to post your code inside the PHP tags…

Hi again,

I have been correcting my code according to your comments. There are many mistakes I totally missed, thanks for pointing out!

However, the plugin is not working yet; I still don’t know how to load the next/prev page property with the Infinite Scrolling.

And your code for the pagination isn’t working for me either… is there any reason to change it other that a cosmetic one?

Thanks so much!

Did you test the sample code I posted? If it did not work for you, tell us what part did not work.
If it all works but the next/prev buttons, I will look at that…

Hi

Yes, I tested it. Well, it doesn’t load the same page over and over again as it did before. Now it simply doesn’t load anything…

Regarding the prev/next button, it doesn’t work. It outputs a piece of raw code. Anyhow this is secondary, my goal is to make the IS work.

Thanks!

Well, my code worked on my system… So, post your version of it and we can see what happens with it.
If it does not work as-is, then you must have changed something… Post your code inside of PHP tags
and we will sort it out for you…

Hi again!

Just tried the exact same code you pasted (with your changes). As I understood, this one should work?

What happens is, when I press the prev/next buttons it sends me to: /test.php?pg=0
It actually outputs a piece of raw code: /test.php?pg= <?= $pageNumber +1; ?>

The previous page doesn’t load with infinite scrolling either. When I press ‘Load more’ at the top of the page t loads the same page-name -1: -2, -3, -4, -5 and so forth.

Next page is also not loading, when I reach the end of the page it just loads the same page over and over again. The good thing is, it doesn’t count the same page-name +1, like it did before.

Thanks so much!

Well, again, you did not post your code. I am sure the code that is posted is because you have
the wrong quotes inside of other quotes. So, show the paging section of code and we can show
you how to fix it. Or, so all of the code, inside of PHP tags of course and I can test it…

Hi.
It has been a long time until I could get back to this. But I am happy to tell it works all fine now! :smiley:

The only thing left to do is to invert the order of the displayed images, sorting the images with the higher numbers in the title first. How can I invert the sorting?

Thanks a lot!

This is the code I have:

[php]

				<!-- Item Post -->
				<div class="post">

				<table cellpadding="4" cellspacing="0" width="760">

				<?php
					$dir   = 'img/'; // Directory for images
					$filetype = '*.*'; // Files
					$allow = array('jpg','jpeg', 'JPEG', 'JPG', 'gif', 'GIF', 'png', 'PNG'); // Files allowed in the array
					$files = glob($dir.$filetype);

					$i=0;
					$open = opendir($dir);
	
					// Get filenames from directory, get extension and if the extension is valid, store in array using numerical indexing
					while (($file=readdir($open))!==false) {
    				$ext=str_replace('.', '', strrchr($file, '.'));
    				if (in_array($ext, $allow)) 
    				$list[$i++]=$file; }

					$perPage= 5; // Number of images per page
					$total=count($list); // Number of images to show in total
					$pages=ceil($total/$perPage); // Number of pages: the number of images divided by how many per page

					$thisPage=isset($_GET['pg'])?$_GET['pg']-1:0; // did user select a specific page? Note, pages on web are counted from 1 (not zero) so must subtract 1 for correct indexing
					$start=$thisPage*$perPage; // calculate starting index into list of filenames
					$pageNumber= $thisPage+1;

					$perRow= 1; // Number images per row
	
					$imgCnt=0; // used to count number of images displayed and hence whether to wrap page. note, could use "for" index $i but this is computationally quicker
					for ($i=$start;$i<$start+$perPage;$i++) {
  
  					// may be too few images to fill page, so check if we have a valid array index. if we don't output empty table cell so fussy browsers
  					// don't mis-display table due to missing cells
  	
  					echo "<div class='item' 'hyphenate'>";
  	
  					if (isset($list[$i])) {
    					
    					echo "<figure>";
    					
						echo '<div class="photo">';
						// Image
    					echo '<img src="'.$files[$i].'" alt="">';
    					
    					echo "</div>"; // Photo
    					
    						echo "<figcaption>";					
							
								// Here it goes the caption		
							
						echo "</figcaption>";		
						
						echo "</figure>";			
			
					echo "</div>"; // item
					
					}else {
    				echo "<td></td>"; // create an empty td
					}
    
  					$imgCnt+=1; // increment images shown
  					if ($imgCnt%$perRow==0) // if image count divided by number to show per row has no remainder then it's time to wrap
    				echo "</tr><tr>";
					}
					echo "</tr>";
	
					closedir($open);
				?>
				</table>		

				</div> <!-- post -->
				

		<!-- Pagination list -->
		<ul id="pagination">
    		<li class="prev">
    		<?php if ($pageNumber > 1) : ?><a href="history.php?pg=<?= $pageNumber - 1; ?>">Prev</a><? endif ?>
    		</li>
    		<li class="next">
    		<? if ($pageNumber < $pages) : ?><a href="history.php?pg=<?= $pageNumber + 1; ?>">Next</a><? endif ?>
    		</li>
		</ul>


		<!-- Call js -->
		<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
		<script type="text/javascript" src="js/jquery-ias.min.js"></script>
		
		
        <!-- IAS bidirectional scrolling w. browser history -->
		<script type="text/javascript">
			var ias = $.ias({
  			container:  "#base-container",
  			item:       ".item",
  			pagination: "#pagination",
  			next:       ".next a",
  			delay:      1000
			});
			ias.extension(new IASSpinnerExtension({ src: 'bundles/spinner.gif' }));
			ias.extension(new IASTriggerExtension({ offset: 100, text: 'Load more' }));
			ias.extension(new IASNoneLeftExtension({text: 'You reached the end.'}));
			ias.extension(new IASPagingExtension());
			ias.extension(new IASHistoryExtension({ prev: '.prev a' }));
		</script>

	</div> <!-- div main -->
</div> <!-- div container -->

[/php]

GREAT! Glad you got it all working correctly. Always a nice warm fuzzy feeling when a project works!

CYA in the bitstream…

Sponsor our Newsletter | Privacy Policy | Terms of Service