ACF Repeater Field | Load More - php

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.

Related

How to check the body tag if it has a class name of "single-product" using php?

I need an if statement that checks the body tag if it has a class name of "single-product" using php? I need to echo a function in a single product page only of woocommerce of wordpress.
This is the code that I would like to show only for single product pages that uses woocommerce.php
<div id="from_product_page">
<?php
$recent = new WP_Query("page_id=235");
while($recent->have_posts()) : $recent->the_post();?>
<?php the_title(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
</div>
You can do something like this:--
$body_classes = get_body_class();
if(in_array('single-product', $body_classes))
{
//Single product page
} else {
//Other Page
}
get_body_class() will return all body classes with array...
PHP can't detect the body tag class of the current page, but you could use javascript or jquery to detect it and then trigger an ajax call to a php. You may be to use a client-server-client sequence.
<script>
if ( $('body').hasClass('single-product') ) {
$('#some_input').val('single-product');
}
$.getJSON( 'gAjax.php?whatever=' + $('#whatever').val(), null, function(jdata) {
var jObj = $.parseJSON(jdata); //RETURNED DATA
...
<script>
Example of conditioning
if($your_varname == 'single-product'){ //your condition
//your criteria
}

Generate more content as user scrolls without sql

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.

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

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

dMultiple Ajax Requests on one page

In my index page I got 3 colums, the first column displays all the categories in a database, second column displays the subject when a category is clicked, and third col selects contents when subject is clicked ..
What Im trying to do is, While Clicking any category, Ajax Requests the database for all subjects related to that category, and display it in column1 and It Works, but when i click the generated subjects to get content for that subject it fails to request asynchronously, instead it takes me to content.php. to make it more clear i am pasting the index.php and script.js ( all the javascript and jquery files been included in header.php)
the index page
<?php
include("tpl/header.php");
?>
<div id="navigation">
<ul id="search_form">
<?php
$cat = Category::find_all();
foreach($cat as $category) {
echo '<li value="';
echo $category->cat_id;
echo '" class="myLi" "><a href="subject.php?id=';
echo $category->cat_id;
echo'">';
echo $category->category;
echo '</a></li>';
}
?>
</ul>
</div>
<div id="content1">
<h2>Subjects</h2>
<!-- works -->
</div>
<div id="content2">
<h2>Content</h2>
<!-- doesnt work -->
</div>
<?php
include_layout_template("footer.php");
?>
the js code
$(document).ready(function() {
$(".myLi").click(function(){
var id = this.value;
ajax.open('get', 'subject.php?id=' + encodeURIComponent(id));
ajax.onreadystatechange = function() {
// Pass it this request object:
handleResponse(ajax);
}
ajax.send(null);
return false; // So form isn't submitted.
});
$(".myLi1").click(function(){
var cid = this.value;
ajax.open('get', 'content.php?id=' + encodeURIComponent(cid));
ajax.onreadystatechange = function() {
// Pass it this request object:
handleResponse1(ajax);
}
ajax.send(null);
return false; // So form isn't submitted.
});
function handleResponse(ajax) {
// Check that the transaction is complete:
if (ajax.readyState == 4) {
// Check for a valid HTTP status code:
if ((ajax.status == 200) || (ajax.status == 304) ) {
// Put the received response in the DOM:
var results = document.getElementById('content1');
results.innerHTML = ajax.responseText;
// Make the results box visible:
results.style.display = 'block';
}
} // End of readyState IF.
} // End of handleResponse() function.
function handleResponse1(ajax) {
// Check that the transaction is complete:
if (ajax.readyState == 4) {
// Check for a valid HTTP status code:
if ((ajax.status == 200) || (ajax.status == 304) ) {
// Put the received response in the DOM:
var results1 = document.getElementById('content2');
results1.innerHTML = ajax.responseText;
// Make the results box visible:
results1.style.display = 'block';
}
} // End of readyState IF.
} // End of handleResponse() function.
});
..Well it fails only when I Click the subject on Index page, When I navigate to subject.php and click the link it gives the result asynchronously. so my question is how can i query multiple ajax calls on a single page(i.e in my case "index.php" ) .. any help ?
After the subjects are loaded, you should ajaxify them, but you are ajaxifying them when the document is ready, that is, before they even exist. Your call to $(".myLi1") doesn't match anything.
Another solution would be to attach your event to all elements matching .myLi1 now, or in the future.
With jQuery < 1.7, you can do this with the delegate() method, otherwise, with the on() method.

Categories