O
O
Orkhan Hasanli2018-07-09 19:25:38
WordPress
Orkhan Hasanli, 2018-07-09 19:25:38

Why is ajax loading not working?

Hello!
I am using the following source to create ajax loading custom posts.
https://misha.blog/wordpress/ajax-pagination.html
Faced 2 problems:
1) There is a javascript that displays text when "Read more" is clicked

jQuery( document ).ready(function( $ ) {
$( ".readmore_testimonial a" ).click(function() {
    $(this).closest('.readmore_testimonial').siblings('.text_testimonial').addClass('full_testimonial');
    $(this).closest('.readmore_testimonial').hide();
    return false
  });

});

It works correctly for initially loaded records, but for records that were loaded later, the handler is not hung up and, accordingly, does not work for new records.
2) The second problem is that there are only 8 entries. By default, I display 4, and the rest should be loaded via ajax when the button is clicked. When you click, only 2 records are loaded and the button disappears, although in theory there are still records in the cycle. Below is my entire code:
functions.php
function true_loadmore_scripts() {
  wp_enqueue_script( 'true_loadmore', get_stylesheet_directory_uri() . '/js/loadmore.js', array('jquery') );
}
 
add_action( 'wp_enqueue_scripts', 'true_loadmore_scripts' );

function true_load_posts(){
 
  $args = unserialize( stripslashes( $_POST['query'] ) );
  $args['post_type'] = 'testimonial';
  $args['paged'] = $_POST['page'] + 1;
  $args['post_status'] = 'publish';
 
  query_posts( $args );
  if( have_posts() ) :
    while( have_posts() ): the_post(); ?>
 
    <?php   $image = get_field('testimonial_image');
            $size = 'testimonials';
            $thumb = $image['sizes'][ $size ];
    ?>
                        <div class="review">
                            <div class="images"><a href="#"><img src="<?php echo $thumb; ?>"></a></div>
                            <div class="text-info">
                                <div class="name"><a href="#"><?php the_field('testimonial_name');?></a></div>
                                <div class="desc">
                                    <div class="text_testimonial"><?php the_field('testimonial_text'); ?></div> 
                                    <div class="readmore_testimonial">
                                        <a>Читать полностью...</a>
                                    </div>
                                </div>
                            </div>
                        </div>

    <?php endwhile; endif; die();
}
 
 
add_action('wp_ajax_loadmore', 'true_load_posts');
add_action('wp_ajax_nopriv_loadmore', 'true_load_posts');

javascript (loadmore.js)
jQuery(function($){
    $('#true_loadmore').click(function(){
        $(this).text('Загружаю...'); // изменяем текст кнопки, вы также можете добавить прелоадер
        var data = {
            'action': 'loadmore',
            'query': true_posts,
            'page' : current_page
        };
        $.ajax({
            url:ajaxurl, // обработчик
            data:data, // данные
            type:'POST', // тип запроса
            success:function(data){
                if( data ) { 
                    $('#true_loadmore').text('Загрузить ещё').before(data); // вставляем новые посты
                    current_page++; // увеличиваем номер страницы на единицу
                    if (current_page == max_pages) $("#true_loadmore").remove(); // если последняя страница, удаляем кнопку
                } else {
                    $('#true_loadmore').remove(); // если мы дошли до последней страницы постов, скроем кнопку
                }
            }
        });
    });
});

archive template
<?php 
            $args = array(
                'post_type' => 'testimonial',
                'post_status' => 'publish',
                'posts_per_page' => '4',
            );
            $my_posts = new WP_Query( $args );
            if ( $my_posts->have_posts() ) : 
            ?>
                    <?php while ( $my_posts->have_posts() ) : $my_posts->the_post() ?>
                        <?php   $image = get_field('testimonial_image');
                                $size = 'testimonials';
                                $thumb = $image['sizes'][ $size ];
                        ?>
                        <div class="review">
                            <div class="images"><a href="#"><img src="<?php echo $thumb; ?>"></a></div>
                            <div class="text-info">
                                <div class="name"><a href="#"><?php the_field('testimonial_name');?></a></div>
                                <div class="desc">
                                    <div class="text_testimonial"><?php the_field('testimonial_text'); ?></div> 
                                    <div class="readmore_testimonial">
                                        <a>Читать полностью...</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endwhile ?>
                <?php if (  $wp_query->max_num_pages > 1 ) : ?>
                    <script>
                    var ajaxurl = '<?php echo site_url() ?>/wp-admin/admin-ajax.php';
                    var true_posts = '<?php echo serialize($wp_query->query_vars); ?>';
                    var current_page = <?php echo (get_query_var('paged')) ? get_query_var('paged') : 1; ?>;
                    var max_pages = '<?php echo $wp_query->max_num_pages; ?>';
                    </script>
                    <!-- <div id="true_loadmore">Загрузить ещё</div> -->
                    <div id="true_loadmore" class="load-more"><a>Загрузить все</a></div>
                <?php endif; ?> 
            <?php endif ?>


What's my mistake? Why does the button disappear after the first click, instead of loading all posts?
Thank you in advance)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tyzberd, 2018-07-09
@azerphoenix

1 item
https://learn.javascript.ru/event-delegation
api.jquery.com/on

$( "#dataTable tbody" ).on( "click", "tr", function() {
  console.log( $( this ).text() );
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question