Jquery Infinite-Scroll not infinite past page 2 - php

I'm using infinite scroll with dynamic data but can't seem to get past page 2...
When the page initially loads I have an offset in the URL so we start at 0, so,
test2.html?offset=0
this is the code to load the date
$offset = $_GET['offset'];
$data = mysql_query("select * from list limit 30 offset $offset;",$db);
echo '<div id="wall" class="transitions-enabled infinite-scroll clearfix">';
while ($databack33 = mysql_fetch_array($data)){
echo '<div class="block">';
echo '';
echo '</div>';
}
Then to load the next page i use:
<nav id="page-nav">
<? $offset = $offset+30; ?>
</nav>
This works ok for pages one and two but it then tells me no more pages to load although there is more data.
If I look at the page source it is correct test2.html?offset=60
this is the masonry/infinite scroll set up
<script type="text/javascript">
$(function(){
var $container = $('#wall');
$container.imagesLoaded(function(){
$container.masonry({
itemSelector: '.block',
isAnimated: true,
animationOptions: {
duration: 750,
easing: 'linear',
queue: false
}
});
});
$container.infinitescroll({
navSelector : '#page-nav', // selector for the paged navigation
nextSelector : '#page-nav a', // selector for the NEXT link (to page 2)
itemSelector : '.block', // selector for all items you'll retrieve
loading: {
finishedMsg: 'No more pages to load.',
img: 'http://i.imgur.com/6RMhx.gif'
}
},
// trigger Masonry as a callback
function( newElements ) {
// hide new items while they are loading
var $newElems = $( newElements ).css({ opacity: 0 });
// ensure that images load before adding to masonry layout
$newElems.imagesLoaded(function(){
// show elems now they're ready
$newElems.animate({ opacity: 1 });
$container.masonry( 'appended', $newElems, true );
});
}
);
});
</script>

To get infinitescroll working with "offset=" pagination I did the following:
Store the current 'next page' url, and get the offset value.
var nextSelector = '#page-nav a';
var origNextUrl = $(nextSelector).attr('href');
var offsetRegex = /(offset=)([0-9]+)/;
var offset = origNextUrl.match(offsetRegex)[2];
Then in infinitescroll assign a function to the 'path' option which accepts a page number and returns the url used to load the next page.
$container.infinitescroll({
// other options
path: function(pageNum) {
return origNextUrl.replace( offsetRegex, ("$1" + (offset * pageNum)) );
},
//callback
});

Related

jQuery infinite scroll issue on a masonry gallery

I'm using jQuery Infinite-Scroll plugin for a masonry gallery. Masonry gallery working without any issue. But infinite scroll loads next page before reaching the bottom.also loading image not showing always.
index.php
<?php
$con = mysqli_connect('localhost','root','root','database');
$per_page = 10;
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else {
$page=1;
}
$start_from = ($page-1) * $per_page;
$query = "SELECT * FROM data ORDER BY rand() LIMIT $start_from, $per_page";
$result = mysqli_query ($con, $query);
while ($row = mysqli_fetch_array($result)) {
?>
<div id="gallery">
<ul id ="container" class="transitions-enabled infinite-scroll clearfix">
<li class="item">item 1</li>
<li class="item">item 2</li>
<li class="item">item 3</li>
</ul>
<?php } ?>
<nav id="page-nav">
</nav>
</div>
I think this issue related to this PHP codes because jQuery script codes are working without any issue. somehow this php codes loading 10 images for next page from database. Please can I have a good PHP code for infinite scroll more than this?
script.js
$(function(){
var $container = $('#container');
$container.imagesLoaded(function(){
$container.masonry({
itemSelector: '.item',
columnWidth: 100
});
});
// infinite scroll options...
$container.infinitescroll({
navSelector : '#page-nav', // selector for the paged navigation
nextSelector : '#page-nav a', // selector for the NEXT link (to page 2)
itemSelector : '.item', // selector for all items you'll retrieve
loading: {
finishedMsg: 'No more pages to load.',
img: 'http://i.imgur.com/6RMhx.gif'
}
},
// trigger Masonry as a callback
function( newElements ) {
var $newElems = $( newElements ).css({ opacity: 0 });
$newElems.imagesLoaded(function(){
$newElems.animate({ opacity: 1 });
$container.masonry( 'appended', $newElems, true );
});
}
);
});

Isotope + Wordpress - re-layout after posts load?

I am using Isotope with a masonry layout in WordPress, along with ImagesLoaded. Each post is a separate isotope item. All seems to be working well, except when I load something dynamic in the post, like a twitter widget or a embedded video. The initial height of the item is set before the post/widget has loaded. Once it has fully loaded, I need isotope to re-layout again to accommodate the new height.
Is there a way to call the layout function again after all the posts are fully loaded?
Here is my isotope code:
// init isotope
var $container = $('#cards');
$container.isotope({
itemSelector: '.item',
masonry: {
columnWidth: '.grid-sizer',
isFitWidth: true
}
});
// layout Isotope again after all images have loaded
$container.imagesLoaded( function() {
$container.isotope('layout');
});
// infinite scroll
$container.infinitescroll({
navSelector : '.pagination',
nextSelector : '.pagination a',
itemSelector : '.item-scroll',
behavior: "twitter",
loading: {
finishedMsg: 'No more pages to load.'
}
},
function ( newElements ) {
var $newElems = jQuery( newElements ).hide(); // hide to begin with
// ensure that images load before adding to masonry layout
$newElems.imagesLoaded(function(){
$newElems.fadeIn(); // fade in when ready
$container.isotope( 'appended', $newElems );
});
}
);
function onLayout() {
$container.infinitescroll('scroll');
}
Thank you for your help!
Try this:
var $container = $('#cards');
$container.imagesLoaded( function() {
// init isotope
$container.isotope({
itemSelector: '.item',
masonry: {
columnWidth: '.grid-sizer',
isFitWidth: true
}
});
});
// infinite scroll
$container.infinitescroll({
navSelector : '.pagination',
nextSelector : '.pagination a',
itemSelector : '.item-scroll',
behavior: "twitter",
loading: {
finishedMsg: 'No more pages to load.'
}
},
function ( newElements ) {
var $newElems = jQuery( newElements ).hide(); // hide to begin with
// ensure that images load before adding to masonry layout
$newElems.imagesLoaded(function(){
$newElems.fadeIn(); // fade in when ready
$container.isotope( 'appended', $newElems ).isotope('layout');
});
}
);
function onLayout() {
$container.infinitescroll('scroll');
}

Image cache clearing issue

I am using jquery to open popups. My popup content consist of image and text.
When I click pop1 I get my pop1 content. When I click pop2 for few seconds I see my pop1 content and then my pop2 loads. How can I fix this?
my popup code:
$(document).ready(function(){
///////LINKS - POPUP////////
$('#all').delegate('a.pop-lnk', 'click', function(){
var page = $(this).attr('id');
$('#popup').empty();
$('#gr-out').css({ opacity: 0.7, 'width':$(document).width(),'height':$(document).height()}).show();
$('#popup').css({'display': 'block'});
$('#popup').load("../phpHandler.php?page="+ page);
})
$('body').delegate('.hide-it', 'click', function(){
$('.hide-it').hide();
})
});
my php that handles the links (phpHandler):
<?php
$page = $_GET['page'];
$pages = array('pop1',
'pop2');
if (!empty($page)) {
if(in_array($page,$pages)){
$page .= '.php';
require_once('../' . $page . '');
}
else require_once('../err.php');
}
else require_once('../err.php');
?>
That is because you first show the element containing the previously loaded pop1 content
$('#gr-out').css({ opacity: 0.7, 'width':$(document).width(),'height':$(document).height()}).show();
$('#popup').css({'display': 'block'});
and then you start to load the new content
$('#popup').load("../phpHandler.php?page="+ page);
It is not a caching but a timing issue :)
Show the popup in a .load callback so that the html is loaded before you show it.
$('#popup').load("../phpHandler.php?page="+ page, function(){
$('#popup').css({'display': 'block'});
});
When you hide your modal, clear out its contents.
$('body').delegate('.hide-it', 'click', function(){
$('.hide-it').hide();
$('#popup').empty();
})
});

Wordpress + Masonry + Infinite Scroll + Fancybox + php SESSION variables

session_start();
$_SESSION["SESSIONaltValue"] = $_POST["galleryValue"];
I'm building a Wordpress site for a client who has a page with heaps of images. I have set up a script to call in all the images in to Masonry, using Infinite Scroll and it works well.
When the user clicks on an image, fancybox launches. I am passing in the ID of the post in to the image and picking it up with jQuery. I've made the ID a variable in jQuery and I'm trying to pass it to php. I've got some script running to POST the variable using ajax. This points to a php page which updates the SESSION. I then echo back the SESSION name in php for testing.
I have set up Wordpress by adding this in to my functions.php file:
// Allow sessions
add_action('init', 'myStartSession', 1);
add_action('wp_logout', 'myEndSession');
add_action('wp_login', 'myEndSession');
function myStartSession() {
if(!session_id()) {
session_start();
}
}
function myEndSession() {
session_destroy ();
}
It does work, but only once and I can't seem to update the SESSION each time I click an image. Any ideas? Here is the code:
jQuery:
jQuery(function(){
var $container = jQuery('#pageRowMasonry');
$container.imagesLoaded(function(){
$container.masonry({
itemSelector: '.pageGalleryContainer',
columnWidth: 100
});
});
$container.infinitescroll({
navSelector : '.page-nav', // selector for the paged navigation
nextSelector : '.page-nav a', // selector for the NEXT link (to page 2)
itemSelector : '.pageGalleryContainer', // selector for all items you'll retrieve
loading: {
finishedMsg: 'No more pages to load.',
img: 'http://i.imgur.com/6RMhx.gif'
}
},
// trigger Masonry as a callback
function( newElements ) {
// hide new items while they are loading
var $newElems = jQuery( newElements ).css({ opacity: 0 });
// ensure that images load before adding to masonry layout
$newElems.imagesLoaded(function(){
// show elems now they're ready
$newElems.animate({ opacity: 1 });
$container.masonry( 'appended', $newElems, true );
});
jQuery(newElements).each(function() {
// Image hovers
jQuery(this).on("hover",function(){
jQuery(this).find('img').toggleClass('pageGalleryContainerImageRollover');
jQuery(this).find('h3').toggleClass('displayNone');
});
jQuery(this).on("click",function(){
jQuery.ajax({
type: 'POST',
url: 'http://beta.website.com/wp-content/themes/photographersinc/update-session.php',
data: {
galleryValue: jQuery(this).find('img').attr("alt")
}
});
});
// Fancybox
jQuery("a.fancybox").fancybox({
// fancybox API options here
'padding': 10,
'titlePosition' : 'over',
'titleFromAlt' : true,
'onComplete': function(){
jQuery('#fancybox-title-over').append(' test ');
jQuery('#fancybox-title-over').append(' <?php echo $_SESSION['SESSIONaltValue']; ?> ');
}
});
});
});
});
php script on update-session.php:
session_start();
$_SESSION["SESSIONaltValue"] = $_POST["galleryValue"];
Note: Have just edited the script. Have added in the call to the update-session.php file using on click. Still only getting the same value in SESSION and not updating.
Looks like you're not waiting for your AJAX to complete before opening the lightbox. Here's an updated snippet that should fix your issue (All I did was move the lightbox code into the done handler).
jQuery(newElements).each(function() {
// Image hovers
jQuery(this).on("hover",function(){
jQuery(this).find('img').toggleClass('pageGalleryContainerImageRollover');
jQuery(this).find('h3').toggleClass('displayNone');
});
jQuery(this).on("click",function(){
jQuery.ajax({
type: 'POST',
url: 'http://beta.website.com/wp-content/themes/photographersinc/update-session.php',
data: {
galleryValue: jQuery(this).find('img').attr("alt")
}
}).done(function(data){
// Fancybox
jQuery("a.fancybox").fancybox({
// fancybox API options here
'padding': 10,
'titlePosition' : 'over',
'titleFromAlt' : true,
'onComplete': function(){
jQuery('#fancybox-title-over').append(' test ');
jQuery('#fancybox-title-over').append(data);
}
});
});
});
});
After submitting I realize this still wouldn't accomplish what you are trying to do. In your PHP that handles the ajax, all you need to do is echo the value you want to load. I've updated the above code to do that.
Here's the updated PHP:
// Maybe you still want to save this in session so its there without AJAX on
// page load so I'll leave this in
session_start();
$_SESSION["SESSIONaltValue"] = $_POST["galleryValue"];
// But what you really want to do is just echo it out so your JavaScript can use
// it in the lightbox
echo $_POST["galleryValue"];
exit;
OK so I have managed to get Masonry working with Infinite scroll on Wordpress, using Fancybox as a plugin to be able to click on the images to make bigger and show some text. The last issue I am having is being able to display the correct data.
Here is what I have in the footer:
jQuery(function(){
var $container = jQuery('#pageRowMasonry');
$container.imagesLoaded(function(){
$container.masonry({
itemSelector: '.pageGalleryContainer',
columnWidth: 100
});
});
$container.infinitescroll({
navSelector : '.page-nav', // selector for the paged navigation
nextSelector : '.page-nav a', // selector for the NEXT link (to page 2)
itemSelector : '.pageGalleryContainer', // selector for all items you'll retrieve
loading: {
finishedMsg: 'No more pages to load.',
img: 'http://i.imgur.com/6RMhx.gif'
}
},
// trigger Masonry as a callback
function( newElements ) {
// hide new items while they are loading
var $newElems = jQuery( newElements ).css({ opacity: 0 });
// ensure that images load before adding to masonry layout
$newElems.imagesLoaded(function(){
// show elems now they're ready
$newElems.animate({ opacity: 1 });
$container.masonry( 'appended', $newElems, true );
});
jQuery(newElements).each(function() {
// Image hovers
jQuery(this).on("hover",function(){
jQuery(this).find('img').toggleClass('pageGalleryContainerImageRollover');
jQuery(this).find('h3').toggleClass('displayNone');
});
jQuery(this).on("click",function(){
jQuery.ajax({
type: 'GET',
url: 'http://beta.website.com/wp-content/themes/photographersinc/update-session.php',
data: { galleryValue: jQuery(this).find('img').attr("alt") },
success: function( msg ) {
jQuery('#fancybox-title-over').html(msg);
}
});
});
// Fancybox
jQuery("a.fancybox").fancybox({
// fancybox API options here
'padding': 10,
'titlePosition' : 'over',
'titleFromAlt' : true
});
jQuery("#fancybox-left").on("click",function(){
jQuery.ajax({
type: 'GET',
url: 'http://beta.website.com/wp-content/themes/photographersinc/update-session-previous.php',
data: { galleryValue: jQuery('#fancybox-content').find('img').attr("alt") },
success: function( msgDirection ) {
jQuery('#fancybox-title-over').html(msgDirection);
}
});
});
jQuery(document).keydown(function(e){
if (e.keyCode == 37) {
jQuery.ajax({
type: 'GET',
url: 'http://beta.website.com/wp-content/themes/photographersinc/update-session-previous.php',
data: { galleryValue: jQuery('#fancybox-content').find('img').attr("alt") },
success: function( msgDirection ) {
jQuery('#fancybox-title-over').html(msgDirection);
}
});
}
});
jQuery("#fancybox-right").on("click",function(){
jQuery.ajax({
type: 'GET',
url: 'http://beta.website.com/wp-content/themes/photographersinc/update-session-next.php',
data: { galleryValue: jQuery('#fancybox-content').find('img').attr("alt") },
success: function( msgDirection ) {
jQuery('#fancybox-title-over').html(msgDirection);
}
});
});
jQuery(document).keydown(function(e){
if (e.keyCode == 39) {
jQuery.ajax({
type: 'GET',
url: 'http://beta.website.com/wp-content/themes/photographersinc/update-session-next.php',
data: { galleryValue: jQuery('#fancybox-content').find('img').attr("alt") },
success: function( msgDirection ) {
jQuery('#fancybox-title-over').html(msgDirection);
}
});
}
});
});
});
});
This now targets a php script depending on next pr previous.
The next script looks like this:
session_start();
if ($_GET['galleryValue']):
$ip = $_GET['galleryValue'];
// Connect to DB
define('DB_HOST', 'XXXXXX');
define('DB_USER', 'XXXXXX');
define('DB_PASS', 'XXXXXX');
define('DB_NAME', 'XXXXXX');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die('Could not connect to MySQL DB ') . mysql_error();
$db = mysql_select_db(DB_NAME, $link);
$sql1 = "SELECT * FROM wp_posts WHERE ID = {$ip}";
$query1 = mysql_query($sql1);
$row1 = mysql_fetch_array($query1);
$sql = "SELECT * FROM wp_posts WHERE post_type = 'gallery' AND post_status = 'publish' AND post_title = (SELECT MIN(post_title) FROM wp_posts WHERE post_title > '".$row1['post_title']."')";
$query = mysql_query($sql);
$row = mysql_fetch_array($query);
// Look for before image in WP_postmeta
$sqlIMG1 = "SELECT * FROM wp_postmeta WHERE meta_key = 'gallery_gallery-before-image_thumbnail_id' AND post_id = '".$row['ID']."'";
$queryIMG1 = mysql_query($sqlIMG1);
$rowIMG1 = mysql_fetch_array($queryIMG1);
$sqlIMG2 = "SELECT * FROM wp_postmeta WHERE post_id = '".$rowIMG1['meta_value']."' AND meta_key = '_wp_attached_file'";
$queryIMG2 = mysql_query($sqlIMG2);
$rowIMG2 = mysql_fetch_array($queryIMG2);
if ($rowIMG2['meta_value'] != '') { $beforeImage = $rowIMG2['meta_value']; }
?>
<span class="fancybox-title"><?php echo $row['post_title']; ?></span>
<span class="fancybox-extraText"><strong>Read more about: </strong>
<?php
// Look for edited item in WP_postmeta
$sqlMETAS1 = "SELECT * FROM wp_term_relationships WHERE object_id = '".$row['ID']."'";
$queryMETAS1 = mysql_query($sqlMETAS1);
while ($rowMETAS1 = mysql_fetch_array($queryMETAS1)) {
$sqlMETAS2 = "SELECT * FROM wp_term_taxonomy WHERE term_taxonomy_id = '".$rowMETAS1['term_taxonomy_id']."'";
$queryMETAS2 = mysql_query($sqlMETAS2);
$rowMETAS2 = mysql_fetch_array($queryMETAS2);
$sqlMETAS3 = "SELECT * FROM wp_terms WHERE term_id = '".$rowMETAS2['term_id']."'";
$queryMETAS3 = mysql_query($sqlMETAS3);
$rowMETAS3 = mysql_fetch_array($queryMETAS3);
if ($rowMETAS3['name'] != 'Gallery') {
if ($rowMETAS3['name'] != 'Gallery (Double)') { ?>
<div class="fancyBoxTagList">
<?php echo $rowMETAS3['name']; ?>
</div>
<?php
}
}
}
?>
</span>
<div class="fancybox-social">
<span><img src="http://beta.website.com/wp-content/themes/photographersinc/images/glyphIcon-Facebook.png" /></span>
<span><img src="http://beta.website.com/wp-content/themes/photographersinc/images/glyphIcon-Twitter.png" /></span>
<span><img src="http://beta.website.com/wp-content/themes/photographersinc/images/glyphIcon-GooglePlus.png" /></span>
<span><a target="_blank" href="http://pinterest.com/pin/create/button/?url=<?php echo $row['guid']; ?>" class="pin-it-button pinitBtnOverride" count-layout="horizontal"><img src="http://beta.website.com/wp-content/themes/photographersinc/images/glyphIcon-Pinterest.png" /></a></span>
</div>
<?php if ($beforeImage) { ?>
<script>
jQuery('#fancybox-img').after('<img id="fancybox-img-right" class="fancybox-img-before hidden" src="http://beta.website.com/wp-content/uploads/<?php echo $beforeImage; ?>" style="opacity: 0.1;" />');
setTimeout(function(){
jQuery(".fancybox-img-before").removeClass("hidden");
jQuery(".fancybox-img-before").animate({opacity:'1.0'});
},500)
</script>
<?php } ?>
It is a bit of a hack, but does seem to work. It loads in the next text, tags, adds a social media bar, and also displays a before image on top of the main image in fancybox if there is one.
I think it's to do with loading times, any takers?

JavaScript Isotope classes not loaded after AJAX

I am pulling the 50 most recent records from a mySQL database. Each goes into a DIV which has Isotope and works perfectly - DIVs animate, reset, etc.
Using AJAX to call for the next 50 records using OFFSET, however, the new records load into new DIVs but Isotope's classes are not applied to them (as seen via Web Inspector.)
THE SET UP:
index.php = calls the database when loaded in the browser, Isotope works fine. A link on index.php (a#update_newImages) triggers a listener to load "load-ajax.php".
load-ajax.php = an external page which only has the SQL SELECT and PDO loop. These records load but w/o Isotope applied, thus the problem.
code from index.php
...database connection info and query code go here
$filter = ""; // appears in the echo'd DIV below, for filtering the ISOTOPE divs. Turned off til this injection problem is solved
//ISOTOPE SETTINGS, in <HEAD>
var $container = $('#theContent');
$container.isotope({
layoutMode : 'fitRows', //leave blank for default masonry
filter: '*',
animationOptions: {
duration: 750,
easing: 'linear',
queue: false,
}
});
in BODY:
<div id="theContent">
<?php
for($i=0; $links = $query_links->fetch(); $i++){
echo "<div class=\"".$filter." box\">" . $links['ATtitle']."<br>" . "#" . $links['LID']."-
". $links['descr']."</div>";
}
?>
</div><!-- theContent -->
<script> // RIGHT BEFORE BODY TAG CLOSES
var offset_newImages = 0; // initial offset value
var newImages = document.getElementById('update_newImages'); // a link on the page
newImages.addEventListener('click', function() {
event.preventDefault();
offset_newImages += 50; // increments batches of records
$.get('load-ajax.php?loadDataType=newImages&offset='+offset_newImages, function(data) {
$("#theContent").hide().html(data).fadeIn(600);
//**EDIT**
alert('Load was performed.'); // callback on success, works - is this where the Isotope "appended" code would go?
}, false);
});
</script>
code from load-ajax.php
...database connection info goes here
$offset = $_GET["offset"]; // from URL
$filter = ""; // for filtering the ISOTOPE divs, turned off til the injection problem is solved
for($i=0; $links = $query_links->fetch(); $i++){
$showList = "<div class=\"".$filter." box\">" . $links['ATtitle']."<br>" . "#" . $links['LID']."-
". $links['descr']."</div>";
echo $showList; // this is where ISOTOPE is not applied after each AJAX injection
}
I am thinking there is a call back solution but am unsure what to do next.
NOTE: I have experimented with the Isotope + infinite scroll by Paul Irish, but cannot use it here until I can convert infinite scroll's paging mechanism to JSON from mySQL. Next project.
EDIT: I have revised index.php to read as follows. The problem persists, but I think it's almost there. The ajax is working, but when Isotope kicks in it does not add its classes on the new DIVs.
<head>
<script type="text/javascript">
$(document).ready(function(){
//ISOTOPE SETTINGS
var $container = $('#container');
$container.isotope({
layoutMode : 'fitRows', //leave blank for default masonry
filter: '*',
animationOptions: {
duration: 750,
easing: 'linear',
queue: false,
}
});
});
</script>
goes right before </body>:
<script>
var offset_newImages = 0; // initial offset value
var newImages = document.getElementById('update_newImages'); // a link on the page
newImages.addEventListener('click', function() {
offset_newImages += 50;
$.ajax({
type: 'GET',
url: "load-ajax.php?offset="+offset_newImages,
success:function(data){
// alert(data); // works
$("#container").hide().html(data).fadeIn(600) // fades in the new recordset
$container.isotope('insert', data);
}
});
});
</script>
So to wrap up, the new data loads into the DIVs - I can see it until I resize the browser window in any way, which is where Isotope kicks in and hides the new DIVs with its CSS.
Isotope has a number of methods for recalculating the layout after dynamically inserting new content.

Categories