How to add numeric pagination to Ajax result, that shows podcasts(custom post) filter by custom taxonomies - ajax

i would like to add numeric pagination (and load the posts dynamically) to this page, called 'page-podcast', where i filter, with Ajax call, my podcast (custom post), using these tags, genre, country and type: https://imgur.com/Qw8JOlC.
In my front end, page-podcast.php, i have this div, where post appears:
<div id="datafetch">Search results will appear here</div>
And in page function.php i added the function that call Ajax
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(e){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: keywords},
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
The following code is the ajax function (always on function.php):
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
...filter part, omitted, because it has nothing to do with the question...
$the_query = new WP_Query($query_args);
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<h2><?php the_title();?></h2>
<?php endwhile;
else: ?>
<p class="no-criteria"><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php
wp_reset_postdata();
endif;
die();
}
Someone has some tips/examples/code to share? Because i tried many solution that i find on the web, but nothing works.

Resolved.
So, i have added the number of the pages within the ajax function, before the end of the loop:
<?php if ($numberPages > 1): ?>
<ul>
<?php
for ($i = 1; $i <= $numberPages; $i++) {
echo '<li><a name="page" href="#" class="pagination" value="' . $i . '">'
. $i . '</a></li>';
}
?>
</ul>
$numberPages is equal to:
$the_query = new WP_Query($query_args);
$numberPages = $the_query->max_num_pages;
I create a global variable, call $page, set to 0.
Then i worked on my two event:
$(document).on("click touchend", ".premuto", function (event) {
event.preventDefault();
page = 1;
keywords['page'] = page;
keywords[$(this).attr('name')] = $(this).attr('value');
fetch(this);
});
$(document).on("click touchend", ".pagination", function (event) {
event.preventDefault();
keywords[$(this).attr('name')] = $(this).attr('value');
fetch(this);
});
".premuto" is an element that contain the id i want to pass to ajax (custom taxonomy) and page is set to 1.
".pagination" is the list of post's page number (1,2,...).
Finally, on my ajax function, i get the page number:
$paged = $_POST['keyword']['page'];
and in my wp_query i added:
'posts_per_page' => '2',
'paged' => $paged,

Related

WP: Trying to update associative array in post_meta with AJAX call

I'm cycling through an associative array and adding each child array as a row in a table.
The last column in that table is a button in which I want to use to remove that array from the parent array in the database.
Here's my markup:
<?php
$response_cost = get_post_meta( 379, '_wc_booking_pricing', true );
?>
<div id="response-cost" class="hidden"><?php echo json_encode( $response_cost); ?></div>
<?php
$i = 0;
foreach ($response_cost as $response) { ?>
<tr id="array-<?php echo $i; ?>">
<!-- table construction -->
<td><button class="remove-array" data-id="<?php echo $i; ?>"><i class="fa fa-times"></i></button></td>
</tr>
<?php
$i++;
};
?>
Here's my jQuery that takes care of removing the child array:
(function($) {
$(document).ready (function () {
$(function(){
var arrString= $('#response-cost').text();
const arr = JSON.parse(arrString);
$('.remove-array').click(function(){
var val = $(this).attr("data-id");
arr.splice(val, 1);
var arr_stringify = JSON.stringify(arr);
$.ajax({
url: ajax_object.ajaxurl,
type: 'POST',
data:{
action: 'update_cost_rule_table_action',
stringified_arr: arr_stringify,
},
success: function( data ){
console.log( data );
}
});
});
});
});
}) (jQuery);
Here's the function in my function.php file:
add_action( 'wp_ajax_update_cost_rule_table_action', 'update_cost_rule_table' );
add_action( 'wp_ajax_nopriv_update_cost_rule_table_action', 'update_cost_rule_table' );
function update_cost_rule_table(){
$response_cost = json_decode($_POST['stringified_arr']);
update_field('_wc_booking_pricing', $response_cost, 379);
wp_die();
}
And here's how I'm enqueuing the script:
function gt21_scripts() {
wp_register_script( 'cost-rule', get_template_directory_uri() . '/js/cost-rule.js', array( 'jquery' ) );
wp_enqueue_script( 'cost-rule' );
wp_localize_script( 'cost-rule', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
};
add_action( 'wp_enqueue_scripts', 'gt21_scripts' );
When I click the button on the front end to remove the corresponding child array, It's currently emptying the whole cell in the dB and therefore removing the row altogether so my table returns empty.

Ajax wipes value of session variable

I recently added an Ajax-powered load more button that loads additional blog posts to my wordpress site. I used the tutorial listed here: https://rudrastyh.com/wordpress/load-more-posts-ajax.html, and it works, but I've ran into another problem.
I have a session variable that counts the current post number. I show 10 posts per page and the counter works for the initial 10. Then I call the next 10 with ajax and instead of counting to 11, 12, 13 etc, it goes back to 1. There's clearly a problem with passing the end value (10) from the template, to the ajax handler in functions. Anyone know what could be wrong? Everything works if I don't use ajax - it's really frustrating.
Template PHP
<?php $_SESSION['the_counter'] = 0; ?>
<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
'posts_per_page' => 10,
'paged' => $paged
);
$my_query = new WP_Query($args);
if($my_query->have_posts()): while($my_query->have_posts()) : $my_query->the_post();
get_template_part( 'template-parts/post/content', get_post_format() );
endwhile;
else:
get_template_part( 'no-results', 'home' );
endif;
if ( $my_query->max_num_pages > 1 ){
echo '</a><div class="misha_loadmore">More posts</div>';
}?>
</div>
<script>var posts_myajax = '<?php echo json_encode( $my_query->query_vars ) ?>',
current_page_myajax = 1,
max_page_myajax = <?php echo $my_query->max_num_pages ?>
</script>
<script src="/loadmore.js"></script>
<?php $my_query = null;
wp_reset_postdata();?>
Ajax Handler in functions.php
function misha_loadmore_ajax_handler(){
$args = json_decode( stripslashes( $_POST['query'] ), true );
$args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
$args['post_status'] = 'publish';
query_posts( $args );
if( have_posts() ) :
// run the loop
while( have_posts() ): the_post();
// look into your theme code how the posts are inserted, but you can use your own HTML of course
// do you remember? - my example is adapted for Twenty Seventeen theme
get_template_part( 'template-parts/post/content', get_post_format() );
// for the test purposes comment the line above and uncomment the below one
// the_title();
endwhile;
endif;
die; }
add_action('wp_ajax_loadmore', 'misha_loadmore_ajax_handler');
add_action('wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler');
Load More JS
jQuery(function($){
$('.misha_loadmore').click(function(){
var button = $(this),
data = {
'action': 'loadmore',
'query': misha_loadmore_params.posts, // that's how we get params from wp_localize_script() function
'page' : misha_loadmore_params.current_page
};
$.ajax({
url : misha_loadmore_params.ajaxurl, // AJAX handler
data : data,
type : 'POST',
beforeSend : function ( xhr ) {
button.text('Loading...'); // change the button text, you can also add a preloader image
},
success : function( data ){
if( data ) {
button.text( 'More posts' ).prev().before(data); // insert new posts
misha_loadmore_params.current_page++;
if ( misha_loadmore_params.current_page == misha_loadmore_params.max_page )
button.remove(); // if last page, remove the button
// you can also fire the "post-load" event here if you use a plugin that requires it
// $( document.body ).trigger( 'post-load' );
} else {
button.remove(); // if no data, remove the button as well
}
}
});
});});
And this is the session code I have on the top of my blog post content template file. It increments the count by 1 for every post.
$counter = $_SESSION['the_counter'];
$counter++;
$_SESSION['the_counter'] = $counter;
At the bottom of the file, I include:
echo insert_counter($the_counter);
At a glance, I'm betting sessions aren't being set. Try adding this to your functions.php file.
add_action('init', function() {
if (!session_id()) {
session_start();
});
This will ensure that sessions are loading on every page. It's worth mentioning that sessions aren't the best way to persist data. I would recommend replacing the session with a cookie.

How can I activate Woocommerce Product Gallery in ajax container?

The new product gallery in Woocommerce is great, but unfortunately I can't get it to work outside the single product template page.
I'm using ajax to load in products in a container on my front page. The ajax call displays the product page: echo do_shortcode('[product_page id="' . $post_id . '"]');. The markup for the gallery is correct, but the .woocommerce-product-gallery container is marked with opacity: 0; and none of the scripts for the gallery is loaded.
How can I implement the gallery functionality with the ajax call and get it working?
Full ajax call:
JQuery
$('.product-modal-toggle').on('click',function(){
var theId = $(this).data('product-id');
var plagg = $(this).data('plagg');
var outfitEnkeltPlaggContainer = $('.outfit-enkelt-plagg');
var parentOutfit = $(this).closest('.outfit').attr('id');
var outfitDescendantContainer = $('#' + parentOutfit + ' .outfit-enkelt-plagg');
$.post('wp-admin/admin-ajax.php', {
action:'my_get_posts',
post_id: theId
}, function(data) {
console.log(data);
outfitDescendantContainer.html(data);
});
});
PHP
/*
** Get Woocommerce Products with Ajax.
** Display Product inside outfit container
*/
function my_get_posts_return() {
global $post;
$post_id = intval(isset($_POST['post_id']) ? $_POST['post_id'] : 0);
if ($post_id > 0) {
$the_query = new WP_query(array('p' => $post_id, 'post_type' => 'product'));
if ($the_query->have_posts()) {
while ($the_query->have_posts()) : $the_query->the_post();
$product = wc_get_product($post_id);
?>
<button class="close-plagg" type="button" name="close-plagg">
<img src="<?php echo get_template_directory_uri(); ?>/library/images/close.svg" alt="Close plagg">
</button>
<?php
echo do_shortcode('[product_page id="' . $post_id . '"]');
// wc_get_template_part( 'content', 'single-product' );
endwhile;
} else {
echo "There were no posts found";
}
}
wp_die();
}
add_action('wp_ajax_my_get_posts', 'my_get_posts_return');
add_action('wp_ajax_nopriv_my_get_posts', 'my_get_posts_return');
PHP
You have to enqueue the scripts of the gallery on your home page :
add_action( 'wp_enqueue_scripts', function(){
if( is_front_page() ){
wp_enqueue_script('zoom');
wp_enqueue_script('flexslider');
wp_enqueue_script('photoswipe-ui-default');
}
});
JS
In the success function of your $.postyou have to call the script :
$( '.woocommerce-product-gallery', data ).each( function() {
$( this ).wc_product_gallery();
} );
Hope this helps

Wordpress ajax request returns 0 in my infinite scroll script

I'd like to implement a very customized infinite scroll. But that comes later, cause i'm already stuck at the ajax request. What's wrong with my code (i get alwas a '0' response even though i have die() in the php function and added nopriv ...)??
my header.php:
<script type="text/javascript">
var count = 2;
var total = <?php echo $wp_query->max_num_pages; ?>;
jQuery(window).scroll(function(){
if (jQuery(window).scrollTop() == jQuery(document).height() - jQuery(window).height()){
if (count > total){
return false;
}else{
loadArticle(count);
//viewsite();
}
count++;
}
});
function loadArticle(pageNumber) {
jQuery.ajax({
url: ajaxurl,
type:'POST',
data: {
action: 'ozinfinite_scroll',
page_no: pageNumber
},
success: function(html){
jQuery("#inf-cont-1").append(html);
}
});
return false;
}
</script>
functions.php:
function ozinfinite_scroll(){
// $loopFile = $_POST['loop_file'];
$paged = $_POST['page_no'];
$posts_per_page = get_option('posts_per_page');
# Load the posts
query_posts(array('paged' => $paged ));
get_template_part( 'contentoz', 'blog' );
die();
}
add_action('wp_ajax_ozinfinite_scroll', 'ozinfinite_scroll'); // for logged in user
add_action('wp_ajax_nopriv_ozinfinite_scroll', 'ozinfinite_scroll'); // if user not logged in
function add_ajaxurl_cdata_to_front(){ ?>
<script type="text/javascript"> //<![CDATA[
ajaxurl = '<?php echo admin_url( 'admin-ajax.php'); ?>';
//]]> </script>
<?php }
add_action( 'wp_head', 'add_ajaxurl_cdata_to_front', 1);
thanks for your help!!
According to the docs http://codex.wordpress.org/AJAX_in_Plugins
you should have something like
echo $someValue
before wp_die() or die()

Ajax Pagination Error in codeigniter

i have the following code which i modiefied from a tutorial
but the problem is that, i cant display the result properly in my view page..
if i display the array in the controller then its working properly, but in the view, its throwing the error..
<?php
class test extends CI_Controller {
public function index($start = 0) {
$this->load->model('pages_model');
$data_page=$this->pages_model->get_pages();
$this->load->helper('url');
$this->load->library('pagination');
$config['base_url'] = base_url().'test/index';
$config['total_rows'] = count($data_page);
$config['per_page'] = 5;
$data['user'] = array();
for($i=$start; $i<$start+$config['per_page']; $i++)
{
if (isset($data_page[$i])) {
$data['user'] = $data_page[$i];
}
}
//print_r($data['user']['page_id']); // this line displays 3, since the tupple with id 3 has maximum priority 5
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
if ($this->input->post('ajax')) {
$this->load->view('test', $data);
} else {
$this->load->view('test', $data);
}
}
}
?>
now comes the model
<?php
class pages_model extends CI_Model{
function __construct() {
parent::__construct();
}
function get_pages()
{
return $this->db->query("SELECT * FROM td_pages ORDER BY page_priority ASC")->result_array();
}
}
?>
and finally the view
<!DOCTYPE html>
<html>
<header>
<title>CodeIgniter Ajax Jquery Pagination</title>
<script src="<?php echo base_url(); ?>assets/front_assets/js/jquery-1.7.1.min.js"></script>
<script>
$(function() {
applyPagination();
function applyPagination() {
$("#ajax_paging a").click(function() {
var url = $(this).attr("href");
$.ajax({
type: "POST",
data: "ajax=1",
url: url,
beforeSend: function() {
$("#content").html("");
},
success: function(msg) {
$("#content").html(msg);
applyPagination();
}
});
return false;
});
}
});
</script>
</header>
<body>
<div id="content">
<div id="data">
<?php foreach($page_frag as $ut)
{?>
<div><?php echo $ut['page_slug'];?></div>
<?php } ?>
</data>
<div id="ajax_paging">
<?php echo $pagination; ?>
</div>
</div>
</div>
</body>
</html>
the problem is that the view is displaying the results in wrong way, but if i display in controller, then it shows that the array in the controller is working perfectly...
please help me solving the prob
You are loading the entire view in your ajax request which also contains the body and head text, Create a seperate view with the following content and load it in your ajax request.
<div id="data">
<?php foreach($page_frag as $ut)
{?>
<div><?php echo $ut['page_slug'];?></div>
<?php } ?>
</div>
What you're doing is WRONG
Pagination is meant to off-load processing power/ram from the server not only from the client side.
You're pulling off all your result then paginate them while you should be asking MySQL to paginate it for you & have a second query to give you the number of results to use it.
If you have index.php in your links then you must be using site_url() instead of base_url() & please note that both accepts an argument so you do not need to concatenate it the way you did it would be like this:
site_url('test/index');
codeigniter uses GET method, while in your javascript code you're using POST.
An easier method would be to catch the pagination li > a tags for the pagination & process it inside a container.

Resources