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?
Related
I create a load more button for load more posts from the database but when I add like button for that if one time clicks on load more button and then click on the like button, like.php file runs two times and adds two lines in likes table. if I click 2 times on load more then like.php file runs 3 times and...
I want to know how I should create a loadmore button and like the button to works fine.
this is simple of my codes:
posts.php :
<div id="comnts2"></div>
<button id="btn2" >load more</button><script>
$(document).ready(function() {
var comco2 = 2;
var offset2 = 0;
$("#btn2").click(function() {
$.ajax({
method: "POST",
url: "ld_comco.php",
data: { comnco2 : comco2, offset2 : offset2}
})
.done(function(msg2) {
$("#btn2").hide();
} else {
$("#comnts2").append(msg2);
});
offset2 = offset2 + comco2;
});
$("#btn2").trigger("click");
});
</script>
ld_comco.php:
<?php
$comnco2=$_POST['comnco2'];
$offset2=$_POST['offset2'];
$rzp=mysqli_query($conn,"SELECT * FROM `tbl_users_posts` WHERE uid = '$uid' ORDER BY id DESC limit $offset2, $comnco2");
while($rp=mysqli_fetch_assoc($rzp)){
$sid=$rz['id'];
$lik=$rz['lik'];
echo $sid."<br>";
/*like*/
echo'<img class="li_ik1" data-id="'.$sid.'" src="pc3/up.png">'.$lik.' Likes</img>';
?>
</span>
<?php }?>
<script type="text/javascript">
$(document).ready(function() {
var uid=<?php echo $uid;?>;
$(document).on("click", ".li_ik1", function() {
var psid = $(this).data('id');
$.ajax({
method: "POST",
url: "like.php",
data: {psid: psid, uid: uid}
}).done();
});
});
</script>
like.php:
<?php
$id=$_POST['psid'];
$uid=$_POST['uid'];
$Y=mysqli_query($conn,"INSERT INTO `t_plik` (pid,uid) VALUES ('$id','$uid')");
$Q=mysqli_query($conn,"UPDATE `tbl_users_posts` SET lik=lik+1 WHERE id='$id'");
?>
thanks
I think the problem is, that you bind your like button multiple times globally. Each time you load the content from ld_comco.php you also call $(document).on("click", ".li_ik1", ...) in the $(document).ready block, which means you bind all ".li_ik1" buttons on the entire document (but some of them has already been bind).
I would remove the $(document).ready(...) block from the ld_comco.php and move the logic into the posts.php right before you render your content. A further positive aspect is you have your business logic at one place.
KEEP IN MIND: You get a response of buttons in msg2, thats why you do not need to filter $msg2 anymore. But if you wrap your buttons with further html tags in ld_comco.php, your buttons will be on a deeper level, so you need to use a selector again, like you did with .on("click", ".li_ik1", ...).
posts.php
...
var $msg2 = $(msg2);
// Now you bind only the loaded buttons instead of
// the buttons in the entire document for multiple times
$msg2.on("click", function() {
var $element = $(this);
var psid = $element.data('id');
var uid = $element.data('uid');
$.ajax({
method: "POST",
url: "like.php",
data: {psid: psid, uid: uid}
}).done();
});
$("#comnts2").append($msg2);
...
In your ld_comco.php you need to add the data-uid="'.$uid.'" and remove the script block. Then your file should look like this:
<?php
$comnco2=$_POST['comnco2'];
$offset2=$_POST['offset2'];
$rzp=mysqli_query($conn,"SELECT * FROM `tbl_users_posts` WHERE uid = '$uid' ORDER BY id DESC limit $offset2, $comnco2");
while($rp=mysqli_fetch_assoc($rzp)){
$sid=$rz['id'];
$lik=$rz['lik'];
echo $sid."<br>";
/*like*/
echo'<img class="li_ik1" data-id="'.$sid.'" data-uid="'.$uid.'" src="pc3/up.png">'.$lik.' Likes</img>';
}
?>
$("#btn2").trigger("click");
this in posts.php means click the #btn2
so after clicking it, you click it again
$(document).ready(function() {
var comco2 = 2;
var offset2 = 0;
$("#btn2").click(function() {
$.ajax({
method: "POST",
url: "ld_comco.php",
data: { comnco2 : comco2, offset2 : offset2}
})
.done(function(msg2) {
$("#btn2").hide();
} else {
$("#comnts2").append(msg2);
});
offset2 = offset2 + comco2;
});
$("#btn2").trigger("click");
});
</script>
I have a modal box that opens content from the footer of a page (a hidden div). I am trying to launch the modal and display the content of another .php file whilst passing a variable that can be used to SELECT from a DB Any ideas?
Here is the code:
The modal box link
Click Me For A Modal
The JS
(function($) {
$('a[data-reveal-id]').live('click', function(e) {
e.preventDefault();
var modalLocation = $(this).attr('data-reveal-id');
$('#'+modalLocation).reveal($(this).data());
});
The .php file with the modalbox content
<div id="myModal" class="reveal-modal">
<div>content called from DB using passed variable</div>
<p>more content</p>
<a class="close-reveal-modal">×</a>
Does anyone have any ideas please?
-----------------------------------------------------------------------------------
UPDATED!
Here is the full js file:
(function($) {
$('a[data-reveal-id').live('click', function(e)
{
e.preventDefault();
var modalLocation = $(this).attr('data-reveal-id');
$.ajax({
url: 'code.php',
data: '$varible',
type: 'GET',
error: function()
{
// If there's an issue, display an error...
},
success: function(output)
{
$('#' + modalLocation).innerHTML(output).reveal( $(this).data() );
}
});
})
$.fn.reveal = function(options) {
var defaults = {
animation: 'fadeAndPop', //fade, fadeAndPop, none
animationspeed: 300, //how fast animtions are
closeonbackgroundclick: true, //if you click background will modal close?
dismissmodalclass: 'close-reveal-modal' //the class of a button or element that will close an open modal
};
var options = $.extend({}, defaults, options);
return this.each(function() {
var modal = $(this),
topMeasure = parseInt(modal.css('top')),
topOffset = modal.height() + topMeasure,
locked = false,
modalBG = $('.reveal-modal-bg');
if(modalBG.length == 0) {
modalBG = $('<div class="reveal-modal-bg" />').insertAfter(modal);
}
//Entrance Animations
modal.bind('reveal:open', function () {
modalBG.unbind('click.modalEvent');
$('.' + options.dismissmodalclass).unbind('click.modalEvent');
if(!locked) {
lockModal();
if(options.animation == "fadeAndPop") {
modal.css({'top': $(document).scrollTop()-topOffset, 'opacity' : 0, 'visibility' : 'visible'});
modalBG.fadeIn(options.animationspeed/2);
modal.delay(options.animationspeed/2).animate({
"top": $(document).scrollTop()+topMeasure + 'px',
"opacity" : 1
}, options.animationspeed,unlockModal());
}
if(options.animation == "fade") {
modal.css({'opacity' : 0, 'visibility' : 'visible', 'top': $(document).scrollTop()+topMeasure});
modalBG.fadeIn(options.animationspeed/2);
modal.delay(options.animationspeed/2).animate({
"opacity" : 1
}, options.animationspeed,unlockModal());
}
if(options.animation == "none") {
modal.css({'visibility' : 'visible', 'top':$(document).scrollTop()+topMeasure});
modalBG.css({"display":"block"});
unlockModal()
}
}
modal.unbind('reveal:open');
});
//Closing Animation
modal.bind('reveal:close', function () {
if(!locked) {
lockModal();
if(options.animation == "fadeAndPop") {
modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
modal.animate({
"top": $(document).scrollTop()-topOffset + 'px',
"opacity" : 0
}, options.animationspeed/2, function() {
modal.css({'top':topMeasure, 'opacity' : 1, 'visibility' : 'hidden'});
unlockModal();
});
}
if(options.animation == "fade") {
modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
modal.animate({
"opacity" : 0
}, options.animationspeed, function() {
modal.css({'opacity' : 1, 'visibility' : 'hidden', 'top' : topMeasure});
unlockModal();
});
}
if(options.animation == "none") {
modal.css({'visibility' : 'hidden', 'top' : topMeasure});
modalBG.css({'display' : 'none'});
}
}
modal.unbind('reveal:close');
});
//Open Modal Immediately
modal.trigger('reveal:open')
//Close Modal Listeners
var closeButton = $('.' + options.dismissmodalclass).bind('click.modalEvent', function () {
modal.trigger('reveal:close')
});
if(options.closeonbackgroundclick) {
modalBG.css({"cursor":"pointer"})
modalBG.bind('click.modalEvent', function () {
modal.trigger('reveal:close')
});
}
$('body').keyup(function(e) {
if(e.which===27){ modal.trigger('reveal:close'); } // 27 is the keycode for the Escape key
});
function unlockModal() {
locked = false;
}
function lockModal() {
locked = true;
}
});//each call
}//orbit plugin call
})(jQuery);
Here is the html trigger:
<a class="big-link" href="#" data-reveal-id="myModal">Click Me to open modal</a>
Here is the code.php, file containing the modal:
<div id="myModal" class="reveal-modal"><div>content called from DB using passed variable</div><p>more content</p><a class="close-reveal-modal">×</a>
The issue at the minute is not passing the variable, but actually lauching the modal with the content of code.php
Thanks again for your time with this problem!
Without knowing what variables you're looking to pass, and what you're trying to grab, you can modify this. I haven't tested it so you may have to do some tweaking.
$('a[data-reveal-id').live('click', function(e)
{
e.preventDefault();
var modalLocation = $(this).attr('data-reveal-id');
$.ajax({
url: 'URL_TO_YOUR_PHP',
data: 'YOUR_VARIABLE', // Look at how to pass data using GET, or POST
type: 'GET' or 'POST', // Choose one, and pass the data above appropriately
error: function()
{
// If there's an issue, display an error...
},
success: function(output)
{
$('#' + modalLocation).innerHTML(output).reveal( $(this).data() );
}
});
})
-- EDIT --
Now the problem is that you don't have #myModal available in your HTML, yet. So, what you want to do is change the following line accordingly:
$('#' + modalLocation).innerHTML(output).reveal( $(this).data() );
-- BECOMES --
$("body").append(output).reveal( $(this).data() );
In your CSS you'll want to initially hide your modal box that way it's revealed appropriately.
I'm trying to create a function that loads more products using Ajax request in Woocommerce. My idea is to create a button "Load more Products" that replace the woocommerce pagination and that loads the 2nd the 3rd etc pages using ajax request. I've created the script that create the load more button with the ajax request and it works, but I'm trying to create a php function that retrive the rest of the products using the ajax request.
Below my code to create the load more button:
<?php
$max_num_pages = $wp_query->max_num_pages;
if ($max_num_pages > 1) {
$output .=
'<script type="text/javascript">
var page = 1,
max_page = '.$max_num_pages.'
jQuery(document).ready(function(){
jQuery(".woocommerce-pagination").hide();
jQuery("#woo_load_more").click(function(){
jQuery(this).hide();
jQuery("#spinner").show();
jQuery.ajax({
type: "POST",
url: "http://demo.ecquadro.com/transport/wp-admin/admin-ajax.php",
data: {
action: "wooPagination",
page: page+1,
per_page: 4,
},
success: function(data, textStatus, XMLHttpRequest){
page++;
jQuery(".prova").append(data);
jQuery("#spinner").hide();
if (max_page > page) {
jQuery("#woo_load_more").show();
}
},
error: function(MLHttpRequest, textStatus, errorThrown){
jQuery("#spinner").hide();
jQuery(this).show();
}
});
});
});
</script>
<div class="woo-products-load">
<span>'.__('Load More Posts', '').'</span>
<img id="spinner" src="'.get_template_directory_uri().'/img/loader.gif" style="display: none;">
</div>';
}
echo $output;
?>
Any idea how to create a function called "wooPagination" that load the rest of the pages?
Thanks in advance.
The esiest solution would probably be to use the infinite-scroll script. You find it here http://www.infinite-scroll.com/
Make you do not delete the normal pagination from the HTML-output and then hook it up as follows(you probably need to change the selectors to fit your site):
var infinite_scroll = {
loading: {
//img: "/img/loading-animation.gif",
msgText: '',
},
nextSelector: ".pagination a.next",
navSelector: ".pagination",
itemSelector: "#main-content ul.products .product-small",
contentSelector: "#main-content ul.products"
};
//Unbind load more on scroll
$(window).unbind('.infscr');
//
$("#load-more-button").click( function() {
$(document).trigger('retrieve.infscr');
});
I have this messaging system (aka wall). It works to add new messages and If I want to cancel the messages loaded from the database. But if I want to cancel the new messages which have just been appended (without reload the page) it doesn't.
$("#wallButton").on("click",function(){
var textdocument = document.getElementById('input_post_wall').value
var poster = '<?php echo escape($userLogged->data()->user_id);?>';
var date = '<?php echo $humanize->humanize()->naturalDay(time());?>';
var time = '<?php echo $humanize->humanize()->naturalTime(time());?>';
var timeNow = '<?php echo time();?>';
if(textdocument.length>0){
$.ajax({
url: '/post_process.php',
type: 'post',
dataType: 'json',
data: {'action': 'post', 'userid': userId, 'poster': poster, 'text':textdocument, 'time':timeNow},
success: function(data) {
var LastID = data["postID"];
var image = data["image"];
var sex = data["sex"];
var name = data["name"];
if(image){
image = "/userImages/"+poster+"/"+poster+".jpg";
}else{
if(sex == 'male'){
image = '/images/male_profile.png';
}if (sex == 'female'){
image = '/images/female_profile.png';
}
}
$('.postDiv').prepend('<div class="post" data-post-id= "'+LastID+'"><img src="'+image+'" class="postImg"><div class="formatted-text"><h4>'+name+'</h4><h5>'+textdocument+'</h5><h6>'+date+' - <span>'+time+'</span></h6><a style="font-size:10px;"class="cancelPost" data-cancel-id= "'+LastID+'">cancel</a></div></div>').hide().fadeIn('slow');
textdocument.val('');
},
}); // end ajax call
}else{
alert('no text');
}
});//end click function
//this cancel post from wall but it only works for the messages displayed when the page has been loaded. I will write the code to cancel the message from database when the jquery part works.
$('.cancelPost').each(function (e) {
var $this = $(this);
$this.on("click", function () {
value = $(this).data('cancel-id');
$('div[data-post-id="'+ value +'"]').fadeOut("slow", function(){ $(this).remove(); });
});
});
this is the php function that fetches all the message from the database when page is loaded.
public function presentPost($userId){
$query = $this->_db->prepare("SELECT * FROM wall WHERE user_ident = ? ORDER BY postId DESC");
if ($query->execute(array($userId))){
$result = $query->fetchAll(PDO::FETCH_OBJ);
foreach ($result as $row) {
$user = New User($row->posterId);
if($user->data()->image == 0){
if($user->data()->sex == 'male'){
$image = '/images/male_profile.png';
}else{
$image = '/images/female_profile.png';
}
}else{
$image = "/userImages/$row->posterId/$row->posterId.jpg";
}
echo'<div class="post" data-post-id= "'.$row->postId.'"><img src="'.$image.'" class="postImg"> <div class="formatted-text"><h4>'.$user->data()->name.' '.$user->data()->lastName.'</h4><h5>'.$row->textPost.'</h5><h6>'.$this->_humanize->naturalDay($row->time).' - <span>'.$this->_humanize->naturalTime($row->time).'</span></h5><a style="font-size:10px;"class="cancelPost" data-cancel-id= "'.$row->postId.'">cancel</a></div></div>';
}
}
}
you should use delegates for that
$(document).on("click",".cancelPost", function () {
value = $(this).data('cancel-id');
$('div[data-post-id="'+value+'"]').fadeOut("slow");
$('div[data-post-id="'+value+'"]').remove();
});
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
});