Generate more content as user scrolls without sql - php

My goal is go generate the following code when the user scrolls down:
<?php
// get all files
$imagesDir = 'uploads/';
$images = glob($imagesDir . '* {jpg,jpeg,png,gif,JPG,JPEG,PNG,GIG}', GLOB_BRACE);
$imagesCount = count($images);
for($i = 0 ; $i < $imagesCount ; $i++) {
// select image
$randomIndex = array_rand($images); // select image index
$file_title = $randomImage = $images[$randomIndex]; // use selected image
unset($images[$randomIndex]); // remove selected image
// print_r($images); // you can see what left in $images
// show image
}
?>
<li class="item-thumbs span3 img">
<!-- Fancybox - Gallery Enabled - Title - Full Image -->
<a class="hover-wrap fancybox" data-fancybox-group="gallery"
title="<?php echo $randomImage ?>" href="<?php echo $randomImage ?>">
<span class="overlay-img"></span>
<span class="overlay-img-thumb font-icon-plus"></span>
</a>
<!-- Thumb Image and Description -->
<img src="<?php echo $randomImage ?>" alt="{Failed To Load Item Description}">
</li>
This code is found inside a block. I want to generate random images and have them show up in a nicely formatted area. Right now, everything works except that I need this code to be automatically generated so more show up as the user scrolls...Just like Facebook loads more posts on the wall when you scroll down. I've tried many scripts but none of them worked for me.

ou query answer is: first thing * you have to set a scroll handler in javascript that will be fired whenever user will scroll either up or down * you have to put ajax call that will fetch result
for you when ever scroll handler will be called * and the last thing render your ajax response
But you have to manage in scroll handler that user is going up or down b / c you will need data whenever user will scroll down
so i am putting some code example , it uses jquery
Scroll handler
var lastScrollTop = 0;
var scrollHandler = function () {
var st = $(this).scrollTop();
var pageHeight = $(document).height();
var pageScrolled = $(window).scrollTop();
var pageView = $(window).height();
if (st > lastScrollTop) {
// downscroll code
if (st > lastScrollTop && (pageScrolled >= (pageHeight / 2))) {
// calling scroll after half page scrolled
// do nothing
} else {
loadMore(); // it will be called only in scroll down
}
}
lastScrollTop = st;
}
put ajax call in this function
function loadMore() {
$(window).off("scroll", scrollHandler);
$.ajax({
url: "",
"data": '',
success: function () {
// render you ajax response
....
$(window).scroll(scrollHandler); // call event handle after first result render
}
});
}
// attaching scroll event after window load
$(window).load(function () {
$(window).scroll(scrollHandler);
});
only the remaining logic is how will you identify that how many result are loaded and wha was last result
so little logic is put an extra parameter in you last that will tell you it was las result
and before calling loadMore(),
read that parameter and send back to ajax call.

Related

ACF Repeater Field | Load More

I am following a Github code to add load more to ACF repeater field. I have 101 fields but load more not working. I tried to bebug too. Ajax response is 0. May be via ajax its not working. Do I have to add anything on functions.php file. Ajax response is 0.
<?php
/*
The code in this file is an example off the code that you would use in your template to
show the first X number of rows of a repeater
I'm sure there are more elegant ways to do the JavaScript, but what's here will work
*/
if (have_rows('gallery_work', 'option')) {
// set the id of the element to something unique
// this id will be needed by JS to append more content
$total = count(get_field('gallery_work', 'option'));
?>
<ul id="my-repeater-list-id">
<?php
$number = 2; // the number of rows to show
$count = 0; // a counter
while( have_rows('gallery_work', 'option') ):the_row();
//the_row();
$image_se_work = get_sub_field('image_se_work', 'option');
?>
<li><img src="<?php echo $image_se_work;?>" alt=""></li>
<?php
$count++;
if ($count == $number) {
// we've shown the number, break out of loop
break;
}
endwhile; // end while have rows
?>
</ul>
<!--
add a link to call the JS function to show more
you will need to format this link using
CSS if you want it to look like a button
this button needs to be outside the container holding the
items in the repeater field
-->
<a id="my-repeater-show-more-link" href="javascript:void(0);" onclick="my_repeater_show_more();"<?php
if ($total < $count) {
?> style="display: none;"<?php
}
?>>Show More</a>
<!--
The JS that will do the AJAX request
-->
<script type="text/javascript">
var my_repeater_field_post_id = <?php echo $post->ID; ?>;
var my_repeater_field_offset = <?php echo $number; ?>;
var my_repeater_field_nonce = '<?php echo wp_create_nonce('my_repeater_field_nonce'); ?>';
var my_repeater_ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
var my_repeater_more = true;
function my_repeater_show_more() {
// make ajax request
$.post(
my_repeater_ajax_url, {
// this is the AJAX action we set up in PHP
'action': 'my_repeater_show_more',
'post_id': my_repeater_field_post_id,
'offset': my_repeater_field_offset,
'nonce': my_repeater_field_nonce
},
function (json) {
// add content to container
// this ID must match the containter
// you want to append content to
$('#my-repeater-list-id').append(json['content']);
// update offset
my_repeater_field_offset = json['offset'];
// see if there is more, if not then hide the more link
if (!json['more']) {
// this ID must match the id of the show more link
$('#my-repeater-show-more-link').css('display', 'none');
}
console.log(json);
},
'json'
);
}
console.log(<?php echo $total;?>);
</script>
<?php
} // end if have_rows
?>
You only have one file of a 2 file example here. This is the code that goes in the template. The PHP side of the this example is in the other PHP file https://github.com/Hube2/acf-dynamic-ajax-select-example/tree/master/repeater-ajax-load-more and includes the WP AJAX action that you need to add to your functions.php file.

load new content on scroll

I am working on an infinite scroll (load data on scroll) plugin for my site.
This is the load.js script:
(function($) {
$.fn.scrollPagination = function(options) {
var settings = {
nop : 10, // The number of posts per scroll to be loaded
offset : 0, // Initial offset, begins at 0 in this case
error : 'No More Posts!', // When the user reaches the end this is the message that is
// displayed. You can change this if you want.
delay : 500, // When you scroll down the posts will load after a delayed amount of time.
// This is mainly for usability concerns. You can alter this as you see fit
scroll : true // The main bit, if set to false posts will not load as the user scrolls.
// but will still load if the user clicks.
}
// Extend the options so they work with the plugin
if(options) {
$.extend(settings, options);
}
// For each so that we keep chainability.
return this.each(function() {
// Some variables
$this = $(this);
$settings = settings;
var offset = $settings.offset;
var busy = false; // Checks if the scroll action is happening
// so we don't run it multiple times
// Custom messages based on settings
if($settings.scroll == true) $initmessage = 'Scroll for more or click here';
else $initmessage = 'Click for more';
// Append custom messages and extra UI
$this.append('<div class="loading-bar">'+$initmessage+'</div>');
function getData() {
// Post data to ajax.php
$.post('ajax.php', {
action : 'scrollpagination',
number : $settings.nop,
offset : offset,
}, function(data) {
// Change loading bar content (it may have been altered)
$this.find('.loading-bar').html($initmessage);
// If there is no data returned, there are no more posts to be shown. Show error
if(data == "") {
$this.find('.loading-bar').html($settings.error);
}
else {
// Offset increases
offset = offset+$settings.nop;
// Append the data to the content div
$this.find('#container123').append(data);
// No longer busy!
busy = false;
}
});
}
getData(); // Run function initially
// If scrolling is enabled
if($settings.scroll == true) {
// .. and the user is scrolling
$(window).scroll(function() {
// Check the user is at the bottom of the element
if($(window).scrollTop() + $(window).height() > $this.height() && !busy) {
// Now we are working, so busy is true
busy = true;
// Tell the user we're loading posts
$this.find('.loading-bar').html('Lade...');
// Run the function to fetch the data inside a delay
// This is useful if you have content in a footer you
// want the user to see.
setTimeout(function() {
getData();
}, $settings.delay);
}
});
}
// Also content can be loaded by clicking the loading bar/
$this.find('.loading-bar').click(function() {
if(busy == false) {
busy = true;
getData();
}
});
});
}
})(jQuery);
This upper script posts data to a php file called ajax.php, which looks like this (shortened):
$sql = "SELECT * FROM table WHERE";
if (!empty($_GET['search'])){
$sql = $sql . " (Name LIKE '%".$_GET['search']."%' OR Description LIKE '%".$_GET['search']."%')";
} else {
$sql = $sql . " Name!=''";
}
$offset = is_numeric($_POST['offset']) ? $_POST['offset'] : die();
$postnumbers = is_numeric($_POST['number']) ? $_POST['number'] : die();
$sql = $sql . " LIMIT ".$postnumbers." OFFSET ".$offset;
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
echo 'item';
}
This ajax.php - script, on the other hand, displays the data in my index.php file.
And here's where the problem is:
Please take a look at the upper if (!empty($_GET['search'])) - statement. Obviously, this $_GET-variable cannot be filled, since the corresponding forms (search-form) are located in my index.php - page.
Now my question is: How can I get the if (!empty($_GET['search'])) to work? I am really not good with ajax, and I believe the problem is that the data created in load.js gets posted to ajax.php in the first place.
Just for completion, this is the corresponding markup in index.php
<section id="start" class="...">
<div id="container123" class="...">
</div>
</section>
<!-- search form etc. -->
Thank you very much in advance. I know it is quite a lot of code. (btw, I know, MySQL is outdated and dangerous)
Modify your plugin to accept search term as parameter and code your index.php something like.
<script>
$("#container123" ).scrollPagination ({ q:'<?php echo $_GET['search']; ?>'"}); </script>
<div id="container123"></div>
Now since this code is written in index.php you will get $_GET['search']

unable to write javascript inside the php page

i have written a javascript inside the php file, but while calling it from my main page like this
<script type="text/javascript" src="<?php echo base_url() . 'js/inf-scroll/javascript_showuserinst.php' ?>"> </script>
Problem: if i see in the javascript_showuserinst.php file a line as $.post('/instruction/show_user_inst/<?php echo $userid; ?>', {
here <?php echo $userid; ?> is giving me problem. Is that line syntax is correct?
I see the view source its showing <b>Notice</b>: Undefined variable: userid in <b>D:\xampp\htdocs\js\inf-scroll\javascript_showuserinst.php</b> on line <b>46</b><br />
But if i copy & paste the same js content in the main page without calling it from external file, it works perfectly.
javascript_showuserinst.php
Header("content-type: application/javascript");
?>
(function($) {
$.fn.scrollPagination = function(options) {
var settings = {
nop : 10, // The number of posts per scroll to be loaded
offset : 0, // Initial offset, begins at 0 in this case
error : 'No More Data To Display!', // When the user reaches the end this is the message that is
// displayed. You can change this if you want.
.............
.............
JavaScript files are expected to contain JavaScript.
Your JavaScript file contains a fragment of HTML.
Don't include HTML <script> tags in a JavaScript file.
<?php
echo "<script type='text/javascript' src='".base_url()."js/inf-scroll/javascript_showuserinst.php"."'></script>"
?>
This must be in your PHP Script File
<script type="text/javascript" src="<?php echo base_url() . 'js/inf-scroll/javascript_showuserinst.php' ?>"> </script>
Now javascript_showuserinst.php can be like below
(function($) {
$.fn.scrollPagination = function(options) {
var settings = {
nop : 10, // The number of posts per scroll to be loaded
offset : 0, // Initial offset, begins at 0 in this case
error : 'No More Data To Display!', // When the user reaches the end this is the message that is
// displayed. You can change this if you want.
delay : 500, // When you scroll down the posts will load after a delayed amount of time.
// This is mainly for usability concerns. You can alter this as you see fit
scroll : true // The main bit, if set to false posts will not load as the user scrolls.
// but will still load if the user clicks.
}
// Extend the options so they work with the plugin
if(options) {
$.extend(settings, options);
}
// For each so that we keep chainability.
return this.each(function() {
// Some variables
$this = $(this);
$settings = settings;
var offset = $settings.offset;
var busy = false; // Checks if the scroll action is happening
// so we don't run it multiple times
// Custom messages based on settings
if($settings.scroll == true) $initmessage = 'No more data to show';
else $initmessage = 'Click for more';
// Append custom messages and extra UI
$this.append('<div class="content"></div><div class="loading-bar">'+$initmessage+'</div>');
function getData() {
// Post data to ajax.php
$.post('/instruction/show_user_inst/<?php echo $userid; ?>', {
action : 'scrollpagination',
number : $settings.nop,
offset : offset
}, function(data) {
// Change loading bar content (it may have been altered)
$this.find('.loading-bar').html($initmessage);
// If there is no data returned, there are no more posts to be shown. Show error
if(data == "") {
$this.find('.loading-bar').html($settings.error);
}
else {
// Offset increases
offset = offset+$settings.nop;
// Append the data to the content div
$this.find('.content').append(data);
// No longer busy!
busy = false;
}
});
}
getData(); // Run function initially
// If scrolling is enabled
if($settings.scroll == true) {
// .. and the user is scrolling
$(window).scroll(function() {
// Check the user is at the bottom of the element
if($(window).scrollTop() + $(window).height() > $this.height() && !busy) {
// Now we are working, so busy is true
busy = true;
// Tell the user we're loading posts
$this.find('.loading-bar').html('Loading...');
// Run the function to fetch the data inside a delay
// This is useful if you have content in a footer you
// want the user to see.
setTimeout(function() {
getData();
}, $settings.delay);
}
});
}
// Also content can be loaded by clicking the loading bar/
$this.find('.loading-bar').click(function() {
if(busy == false) {
busy = true;
getData();
}
});
});
}
})(jQuery);
Try it out

Endless scrolling and using the GET method to filter content

I'm developing a mobile site with endless scrolling to display its content. The endless scrolling is achieved with this script (my implementation of it is below). The script works as it's supposed to.
But some of the content are categorized into different types. On the desktop version without endless scrolling, the types are filtered using the GET method. However, since the actual php for connecting to the database is stored on a separate "ajax.php", the filter parameters contained in GET is not being passed to it, resulting in the ajax.php returning nothing. Is there are way to fix this? Thanks in advance
Page for displaying every:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="javascript.js"></script>
<script>
$(document).ready(function() {
$('#content').scrollPagination({
nop : 5, // The number of posts per scroll to be loaded
offset : 0, // Initial offset, begins at 0 in this case
error : ' ', // When the user reaches the end this is the message that is
// displayed. You can change this if you want.
delay : 500, // When you scroll down the posts will load after a delayed amount of time.
// This is mainly for usability concerns. You can alter this as you see fit
scroll : true // The main bit, if set to false posts will not load as the user scrolls.
// but will still load if the user clicks.
});
});
</script>
</head>
<body>
<div id="content">
<!-- infinite scroll content here -->
</div>
</body>
</html>
javascript.js:
(function($) {
$.fn.scrollPagination = function(options) {
var settings = {
nop : 10, // The number of posts per scroll to be loaded
offset : 0, // Initial offset, begins at 0 in this case
error : ' ', // When the user reaches the end this is the message that is
// displayed. You can change this if you want.
delay : 500, // When you scroll down the posts will load after a delayed amount of time.
// This is mainly for usability concerns. You can alter this as you see fit
scroll : true // The main bit, if set to false posts will not load as the user scrolls.
// but will still load if the user clicks.
}
// Extend the options so they work with the plugin
if(options) {
$.extend(settings, options);
}
// For each so that we keep chainability.
return this.each(function() {
// Some variables
$this = $(this);
$settings = settings;
var offset = $settings.offset;
var busy = false; // Checks if the scroll action is happening
// so we don't run it multiple times
// Custom messages based on settings
if($settings.scroll == true) $initmessage = '顯示更多';
else $initmessage = '顯示更多';
// Append custom messages and extra UI
$this.append('<div class="content"></div><div class="loading-bar">'+$initmessage+'</div>');
function getData() {
// Post data to ajax.php
$.post('ajax.php', {
action : 'scrollpagination',
number : $settings.nop,
offset : offset,
}, function(data) {
// Change loading bar content (it may have been altered)
$this.find('.loading-bar').html($initmessage);
// If there is no data returned, there are no more posts to be shown. Show error
if(data == "") {
$this.find('.loading-bar').html($settings.error);
}
else {
// Offset increases
offset = offset+$settings.nop;
// Append the data to the content div
$this.find('.content').append(data);
// No longer busy!
busy = false;
}
});
}
getData(); // Run function initially
// If scrolling is enabled
if($settings.scroll == true) {
// .. and the user is scrolling
$(window).scroll(function() {
// Check the user is at the bottom of the element
if($(window).scrollTop() + $(window).height() > $this.height() && !busy) {
// Now we are working, so busy is true
busy = true;
// Tell the user we're loading posts
$this.find('.loading-bar').html('載入中...');
// Run the function to fetch the data inside a delay
// This is useful if you have content in a footer you
// want the user to see.
setTimeout(function() {
getData();
}, $settings.delay);
}
});
}
// Also content can be loaded by clicking the loading bar/
$this.find('.loading-bar').click(function() {
if(busy == false) {
busy = true;
getData();
}
});
});
}
})(jQuery);
ajax.php:
<?php
mysql_connect('host', 'username', 'password') or die();
mysql_select_db('database');
#START enable chinese encoding
mysql_query("SET character_set_results=utf8");
#END enable chinese encoding
$offset = is_numeric($_POST['offset']) ? $_POST['offset'] : die();
$postnumbers = is_numeric($_POST['number']) ? $_POST['number'] : die();
$category = mysql_real_escape_string($_GET['category']);
$run = mysql_query("SELECT * FROM table WHERE category='$category' ORDER BY date DESC LIMIT ".$postnumbers." OFFSET ".$offset);
while($row = mysql_fetch_array($run)) {
echo '
<a href="/video/video.php?id=' . $row['id'] . '&relatedgroup=' . $row['relatedgroup'] . '">
<div id="contentitemwrap">
<div id="videostripe"> </div>
<div id="contentitemtitle">
<h2>' . $row['name'] . ' <span class="relatedtype">(' . $row['relatedtype'] . ')</span></h2>
於' . $row['date'] . '發表
<p class="contenttext">' . $row['fbdescription'] . '</p>
</div>
<div id="widescreenimagewrap">
<div id="widescreenimageratio">
</div>
<div id="widescreenimage">
<img id="img100" src="' . $row['thumbnail'] . '" />
</div>
</div>
</div>
</a>
';
}
?>
Assuming you are getting the parameters you want to passed into the hosting page via a query string then you should be able to change your $.post call in getData to:
$.post('ajax.php'+window.location.search, {
action : 'scrollpagination',
number : $settings.nop,
offset : offset,
}, function(data) {
..... the rest of your code

Codeigniter scrollpagination

I am using jquery plugin scrollpagination in codeigniter i am facing problem that my loop does not terminate and alos not giving accurate result.
this is my html code
<div id="main">
<div id='friend_display'>
<?php if($list->num_rows() > 0 ){
foreach($list->result() as $show)
{ ?>
<div class="image-box" style="margin-left:30px" id='image-holder' >
<div class="photo-cover">
<img width="160px" height="117px" src="<?=base_url()?>uploads/user_images/friends/<?php echo $show->user_image;?>" alt="" />
</div>
<p class="photo-name"><b><?php echo $show->user_name;?></b></p>
</div>
<?php } } else { echo '<div align="center" style="color:#FF0000; font-size:17px; font-weight:bold">You have no Friends yet</div>';}?>
<div class="cl"> </div>
</div></div>
this is script
<script type="text/javascript">
var page_num = 1;
$(function(){
$('#friend_display').scrollPagination({
'contentPage': '<?=base_url()?>friends/load_more', // the url you are fetching the results
'contentData': {page_num:$('.image-box').size()}, // these are the variables you can pass to the request, for example: children().size() to know which page you are
'scrollTarget': $(window), // who gonna scroll? in this example, the full window
'heightOffset': 10, // it gonna request when scroll is 10 pixels before the page ends
'beforeLoad': function(){ // before load function, you can display a preloader div
$('#loading1').fadeIn();
},
'afterLoad': function(elementsLoaded){ // after loading content, you can use this function to animate your new elements
$('#loading1').fadeOut();
var i = 0;
$(elementsLoaded).fadeInWithDelay();
page_num:$('.image-box').size();
}
});
// code for fade in element by element
$.fn.fadeInWithDelay = function(){
var delay = 0;
return this.each(function(){
$(this).delay(delay).animate({opacity:1}, 200);
delay += 100;
});
};
});
</script>
and this is my php function
function load_more()
{
$offset = $this->input->post('page_num');
$list = $this->friends_model->show_friends($offset);
if($list->num_rows()>0)
{
foreach($list->result() as $show)
{?>
<div class="image-box" style="margin-left:30px" id='image-holder'>
<div class="photo-cover">
<img width="160px" height="117px" src="<?=base_url()?>uploads/user_images/friends/<?php echo $show->user_image;?>" alt="" />
</div>
<p class="photo-name"><b><?php echo $show->user_name;?></b></p>
</div>
<?php } ?>
<div class="cl"> </div>
<?php
}
else
{
//echo(333);
}
}
in db i jst shoing main query
$this->db->limit(12,$offset);
can someone tell me what i am missing?
Open this Link to wathch complete code.Scroll Pagination
I belive that the way you are fetching offset isn't correct. (Thought I'm not sure because I don't know what is in your POST['page_num'])
$offset = $this->input->post('page_num');
It looks like you fetch the page number, but the offset in limit function should be how much row has to be skipped. So if you are showing 12 results per "tick" offset should be 12*page_number
$this->db->limit(12,$offset*12);
If you leave offset to page number, you will get wrong results:
limit(12,[0,1,2,...]) // items 1-12, 2-13, 3-14 etc...
limit(12,[0,12,24....] //items 1-12, 13-24, 25-32 etc...
Here i solve this problem in my own way you can try this.In your script remove this line
'contentData': {page_num:$('.image-box').size()},
and add this line
'childClass' : '.image-box',
After open scrollpagination.js file then replace this line data: opts.contentData, with this data: {page_num : $(obj).children(opts.childClass).size()},. Again replace 'contentData' : {}, this line with 'childClass' : '.datalist',.
In your function display_friends() please replace exit; function with this line echo '<input type="hidden" id="nodata" value="1" />'; . After that write your script look like this :
$(function(){
$('#nomoreresult').hide();
$('#loading1').hide();
$('#friend_display').scrollPagination({
'contentPage': 'Your_Url', // the url you are fetching the results
// these are the variables you can pass to the request, for example: children().size() to know which page you are
'childClass' : '.image-box',
'scrollTarget': $(window), // who gonna scroll? in this example, the full window
'heightOffset': 10, // it gonna request when scroll is 10 pixels before the page ends
'beforeLoad': function(){ // before load function, you can display a preloader div
$('#loading1').show().fadeIn();
},
'afterLoad': function(elementsLoaded){
// after loading content, you can use this function to animate your new elements
$('#loading1').hide().fadeOut();
$(elementsLoaded).fadeInWithDelay();
if($('#nodata').val() == '1'){
$('#friend_display').stopScrollPagination();
$('#loading1').hide();
$('#nomoreresult').show().fadeIn();
}
}
});
// code for fade in element by element
$.fn.fadeInWithDelay = function(){
var delay = 0;
return this.each(function(){
$(this).delay(delay).animate({opacity:1}, 200);
delay += 1000;
});
};
Did you try jQuery.noConflict()?
<script type="text/javascript">
var page_num = 1;
jQuery.noConflict();
$(function(){...
Edit2:
It seems your offset works wrong. According to http://pastebin.com/MC1KZm8y
Find:
$offset = $this->input->post('page_num');
$list = $this->friends_model->find($offset);
Replace:
$page_line = 6; //for example
$page_num = $this->input->post('page_num');
$offset = ($page_num -1) * $page_line;
$list = $this->friends_model->find($offset);
Add this missing code inside the afterLoad:function(){.. code also this should stop looping your pagination make sure to add exactly same id that you entered for the scrollpagination id <div id='friend_display'>
if ($('#friend_display').children().size() > 100){ //set the condition to where to stop
// if more than 100 results already loaded, then stop pagination (only for testing)
$('#nomoreresults').fadeIn(); //if you want to show message like "No more result!" use this
$('#friend_display').stopScrollPagination();// this is the most important function call
}
inside .scrollPagination({.. change 'contentPage': '<?php echo base_url();?>controller/action' inside this action(){ $this->load->view('that_you_want_to_display'); it means your display_friends() method only should contain the view file that want to load and parse and the data that you want to display and inside that view echo your data using the foreach

Categories