Infinite scroll with jquery and php - php

I use this function to create an infite scrolling on my page. The thing is it displays the default div's (onload) and one batch with divs when i scroll to the bottom. But when i scroll to the bottom once again when the batch is added it won't trigger the loadmore.php function. It says: no more posts to show
What am i doing wrong?
<div id="wrapper">
<div id="postswrapper">
<div class="postitem" id="4"><img src="http://ww.supair.fr/photos_cam1_fixe/image.jpg" /></div><div class="postitem" id="5"><img src="http://www.bormioonline.com/imagesntent/webcam/webcam06-320x240right.jpg" /></div>
</div>
<script type="text/javascript">
var loading = false;
$(window).scroll(function(){
var h = $('#postswrapper').height();
var st = $(window).scrollTop();
// the following tests to check if
// 1. the scrollTop is at least at 70% of the height of the div, and
// 2. another request to the ajax is not already running and
// 3. the height of the div is at least 500.
// You may have to tweak these values to work for you.
if(st >= 0.7*h && !loading && h > 500){
loading = true;
$('div#loadmoreajaxloader').show();
$.ajax({
url: "/test2/loadmore.php?lastid=" + $(".postitem:last").attr("id"),
success: function(html){
if(html){
$("#postswrapper").append(html);
$('div#loadmoreajaxloader').hide();
}else{
$('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
}
loading = false;
}
});
}
});

Related

Load more button not working and showing all the records on the page

I have a page and I am displaying the list(MAX 200 records) on my page using ajax.
I am using the below code to call the ajax and show the response on the page.
And the second script is for a button called "Load More". I have to show the 20 records on the page then the user clicks on load more than displays the next 20 records.
Now, My issue is, I am getting all the records and load more button
$(document).ready(function(){
$.ajax({
url: 'function21.php',
method:'post',
dataType: "json",
data:{action:"employeelist21"},
success: function(data){
$('#employeelist').append(data);
}
})
});
$(document).ready(function(){
var list = $("#employeelist21 li");
var numToShow = 20;
var button = $("#next");
var numInList = list.length;
//alert(numInList);
list.hide();
if (numInList > numToShow) {
button.show();
}
list.slice(0, numToShow).show();
button.click(function(){
var showing = list.filter(":visible").length;
list.slice(showing - 1, showing + numToShow).fadeIn();
var nowShowing = list.filter(":visible").length;
if (nowShowing >= numInList) {
button.hide();
}
});
});
PHP
function employeelist21($pdo)
{
$query=" sql query here";
$stmt = $pdo->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
if (!empty($results)) {
$data='';
$data='<ul><li>
<div class="box">
<div><span>Company</span></div>
<div><span>Industry</span></div>
<div><span>Name</span></div>
<div><span>Location</span></div>
</div>
</li>';
foreach($results as $key){
$data.='<li>
<div class="box">
<div><h4>'.$key['Industry'].'</h4></div>
<div><p>'.$key['industry_name'].'</p></div>
<div><p>'.$key['name'].'</p></div>
<div><p>'.$key['city'].'</p></div>
</div>
</li>';
}
$data.='</ul><div class="text-center">Load More</div>';
}
else{
$data.='No records available';
}
echo json_encode($data);
}
First, I would rather transfer back a list of data (not html) in json format and use that like an array, creating the HTML for it in javascript. BUT we don't always get what we want, so in this case I would assign an attribute to each set of 20 like this:
// at the top of your script (not in a function)
let perPage = 20, onGroup=0
// in your ajax function ...
success: function(data){
$('#employeelist').hide();
$('#employeelist').append(data);
$('#employeelist box').each( function(index) {
if (index===0) return; //header row
$(this).data('group',Math.floor(index-1/perPage))
});
$('#employeelist box').hide()
$('#employeelist box [data-group=0]').show()
$('#employeelist').show();
}
Then for the button, remove this from the PHP and make it an element under the results div
<div class="text-center">Load More</div>
Then in your script
$(document).ready(function() {
$("#next").click(function(){
$('#employeelist box [data-group='+onGroup+']').hide()
onGroup++;
$('#employeelist box [data-group='+onGroup+']').show()
if ($('#employeelist box [data-group='+(onGroup+1)+']').length ===0) {
$(this).hide();
}
});
});
Hard to test here, but let me know if it doesn't work

Php Ajax - Multiple calls in one page

Right now I have this code loading only 1 page (load.php?cid=1 but I want to load 5-8 (cid=1,cid=2,cid=3,cid=4,cid=5,cid=6,cid=10 ...etc )in different div(s).
how will I achieve it ?
$(document).ready(function() {
function loading_show() {
$('#loading_Paging').html("<img src='images/loading.gif'/>").fadeIn('fast');
}
function loading_hide() {
$('#loading_Paging').fadeOut 'fast');
}
function loadData(page) {
loading_show();
$.ajax({
type: "POST",
url: "load.php?cid=1",
data: "page=" + page,
success: function(msg) {
$("#container_Paging").ajaxComplete(function(event, request, settings) {
loading_hide();
$("#container_Paging").html(msg);
});
}
});
}
As JimL alluded to, I would give each element on your page a common class, give each element a unique data attribute like data-cid="1", iterate through each element grabbing the cids and calling the ajax function for each.
Id go a step further by using a promise to get all of the ajax responses then load all the data when the promise has been resolved (when all the ajax requests have been completed).
Here is a working example
The HTML:
<div id="loading_Paging"></div>
<div class="myElements" data-cid="1"></div>
<div class="myElements" data-cid="2" ></div>
<div class="myElements" data-cid="3" ></div>
<div class="myElements" data-cid="4" ></div>
<div class="myElements" data-cid="5" ></div>
<div class="myElements" data-cid="6" ></div>
<div class="myElements" data-cid="7"></div>
<div class="myElements" data-cid="8" ></div>
The jQuery:
$(function() {
var page = 'some string...'
loadData(page);
function loadData(){
$('#loading_Paging').html("<img src='images/loading.gif'/>").fadeIn('fast');
// loop through each image element
// calling the ajax function for each and storing the reponses in a `promise`
var promises = $('.myElements').map(function(index, element) {
var cid = '&&cid=' + $(this).data('cid'); // get the cid attribute
return $.ajax({
type: "POST",
url: 'load.php',
data: "page=" + page +cid, //add the cid info to the post data
success: function(msg) {
}
});
});
// once all of the ajax calls have returned, te promise is resolved
// and the below function is called
$.when.apply($, promises).then(function() {
// arguments[0][0] is first result
// arguments[1][0] is second result and so on
for (var i = 0; i < arguments.length; i++) {
$('.myElements').eq(i).html( arguments[i][0] );
}
$('#loading_Paging').fadeOut('fast');
});
}
});
The PHP I used for my example:
<?php
if (isset($_POST['cid']) ){
// this is just a contrived example
// in your code youd use the cid to
// get whatever data you need for the current div
echo 'This is returned message '.$_POST['cid'];
}
?>

Contents loaded with Ajax lose style

I've create a page that load 10 elements and at the bottom of the page I've placed the classic button "load more" to load 10 more elements.
The problem is with jQuery, the style given by :nth-child() property doesn't work for the next 10 elements and so on.
Is there a solution to solve this problem?
E.g.:
File main.js
$("#main_content > p:nth-child(3n+2)").addClass("small-product-wrapper");
$("#main_content > p:nth-child(3n+3)").addClass("small-product-wrapper");
File example.php
<script type="text/javascript">
$('#more_button').click(function(){
loaded_messages += 10;
$('#loading').ajaxSend(function() {
$("#loading").stop(true,true).fadeIn().delay(200).fadeOut();
});
var dati = "twitterpagination/get_messages/" + loaded_messages;
$.ajax({
url:'twitterpagination/get_messages/' + loaded_messages,
type: 'get',
data: dati,
cache: false,
success: function() {
$.get(dati, function(data){
$("#main_content").append(data);
});
if(loaded_messages >= num_messages - 10) {
$("#more_button").hide();
}
},
error: function() {
// do nothing
}
});
return false;
});
</script>
<div id="main">
<?php
foreach($latest_messages as $message) {
echo '<p>'.$message->message .'</p>';
}
?>
<div id="more_button">more</div>
</div>
File loaded by Ajax url:
<?php
foreach($latest_messages as $message) {
echo '<p>'.$message->message .'</p>';
}
?>
In the file loaded by ajax:
<?php
foreach($latest_messages as $message) {
echo '<p class="small-product-wrapper">'.$message->message .'</p>';
}
?>
Add the style to the returned P tag
You need to re-run those 2 jQuery lines right after the new html is added from your AJAX.
success: function() {
$.get(dati, function(data){
$("#main_content").append(data);
// here
$("#main_content > p:nth-child(3n+2)").addClass("small-product-wrapper");
$("#main_content > p:nth-child(3n+3)").addClass("small-product-wrapper");
});
}
This is because those original lines are run only once when the page is loaded.
When you load new content with Ajax the only way to have the style automatically assigned to it it's to give it a class and have that class style defined in css.
If you don't do that, you have to assign the style again in the callback function of the ajax call.

How to show loading image at load() proccess with js

I want to show loading image in my page..
I have a load() function and i need to display a loading image in the center of my page while its loading and i am using load() with backbone router.
I think i need javascript to do it but i dont know how to show it only at load() proccess.
**You can use in this way**
function showLoadingMsg() {
$('#loading-message').css({
display : 'block'
});
}
function hideLoadingMsg() {
$('#loading-message').remove();
}
**the place where you want to show loading gif**
<!--loding image goes here-->
<div style="display:none" id="loading-message"><img src="<?php echo base_url(); ?>assests/img/loading.gif" /></div>
**When to show and hide should be in**
obj.fbId ="14232";
showLoadingMsg();
$.post("<?= base_url() ?>welcome/insertVideos",obj,
function(success){
hideLoadingMsg();
}, "json");
I am also php developer i did this using jquery..
You can use it through Jquery like this:-
Just confirm your jquery script are present..
<div id="popup1" class="popup_block">
<?php echo $this->Html->image('loader2.gif'); ?>
<h4>Processing Please Wait...! </h4>
</div>
And you have to call this function
function open_loader(){
if(enrollFlag==0){
return false;
}
//Fade in Background
jQuery('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
jQuery('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer
var popID = 'popup1';
//var popWidth = 500;
//Fade in the Popup and add close button
jQuery('#' + popID).css({ 'width': '250' });
//Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accomodate for the padding + border width defined in the css
var popMargTop = (jQuery('#' + popID).height() + 80) / 2;
var popMargLeft = (jQuery('#' + popID).width() + 80) / 2;
//Apply Margin to Popup
jQuery('#' + popID).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft,
'display' : 'block'
});
}
This function will show loader image when it will execute..
Or if you stick to load()
do like this:-
<input type="button" onclick="example_request()" value="Click Me!" />
<div id="example-placeholder">
<p>Placeholding text</p>
</div>
function example_ajax_request() {
$('#example-placeholder').html('<p><img src="/images/loader.gif" width="220" height="19" /></p>');
$('#example-placeholder').load("/examples/loaded.html");
}
Lets say you have a div with image tag in it.. If you have ajax request than You can show or hide the div like this... (place this code on .ready function)
$('#loadingDiv')
.hide() // hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
});
And if you do not have ajax call than use like this....
function Load()
{
$('#loadingDiv').hide(); // hide it initially
$('#loadingDiv').show() ;
//-------------Your code here of form loading------
//-------------Your code here of form loading------
//-------
//-------
$('#loadingDiv').hide();// hide it in the last
}

jQuery cubes overlap eachother sometimes

I have a pinterest style site and made a jquery script that spaces the cubes evenly no matter how big the browser is. For some reason on page load it has some overlapping cubes which didn't exist before. I talked with the guy that helped me make it and he said it's probly because of the code before the code that creates the blocks and positions them. It crashes the javascript.
I think it's because of the $(window).scroll ajax loading code but I can't seem to pinpoint the problem. I tried moving positionBlocks(); around and nothing changes. If you load the page in your browser and then change your browser size then it positions them correctly but obviously I want it to look right when the user first gets there.
function setupBlocks() {
windowWidth = $(window).width();
blocks = [];
// Calculate the margin so the blocks are evenly spaced within the window
colCount = Math.floor(windowWidth/(colWidth+margin*2));
spaceLeft = (windowWidth - ((colWidth*colCount)+margin*2)) / 2;
spaceLeft -= margin;
for(var i=0;i<colCount;i++){
blocks.push(margin);
}
positionBlocks();
}
function positionBlocks() {
$('.block').each(function(i){
var min = Array.min(blocks);
var index = $.inArray(min, blocks);
var leftPos = margin+(index*(colWidth+margin));
$(this).css({
'left':(leftPos+spaceLeft)+'px',
'top':min+'px'
});
blocks[index] = min+$(this).outerHeight()+margin;
});
}
// Function to get the Min value in Array
Array.min = function(array) {
return Math.min.apply(Math, array);
};
var curlimit=<?php echo $curlimit; ?>;
var totalnum=<?php echo $num_rws; ?>;
var perpage=<?Php echo $perpage ?>;
var working_already=false;
$(document).ready(function() {
//($(window).scrollTop() + $(window).height() )> $(document).height()*0.8
// old ($(window).scrollTop() + $(window).height() == $(document).height())
$(window).resize(setupBlocks);
$(window).scroll(function() {
if(($(window).scrollTop() + $(window).height() )> $(document).height()*0.90 && totalnum>0 && working_already==false ) {
} else return false;
working_already=true;
$("div#loading_bar").fadeIn("slow");
curlimit=curlimit+perpage;
$("div#loading_data_location").html("");
$.get('get_cubes.php?page=<?php echo $_GET['page'] ?>&curlimit='+curlimit, function(response) {
$("div#loading_data_location").html(response);
$("div#ColumnContainer").append($("div#loading_data_location").html());
$("a#bigpic").fancybox({
'onComplete' : imageLoadComplete,
'onClosed' : imageClosed,
'type': 'ajax' });
if ($("div#loading_data_location").text()=="")
totalnum=0;
else
totalnum=<?php echo $num_rws; ?>;
$('.like:not(.liked)').click(like_box);
$('.save:not(.saved)').click(save_box);
$('.follow:not(.following)').click(follow);
$("div#loading_bar").fadeOut("fast");
$("div#loading_data_location").html('');
setupBlocks();
working_already=false;
});
});
I had to add this to the end of my script:
<script language="javascript">
$(window).bind("load", function() {
setupBlocks();
});
</script>
and then this to the end of the on scroll ajax load. Sometimes jquery just needs a little kick in the face haha:
setTimeout(function(){setupBlocks();},100);

Categories