分页不工作AJAX请求

问题描述:

I want to make a pagination of the results of the AJAX request. Pagination does not work. After clicking the page number, only the address and everything (example: / page / 3 /) change. Where did I make a mistake?

PAGE.PHP

<div class="site-content clearfix">
       <h1>Alex Blog</h1>
        <?php
          $ourCurrentPage = get_query_var('paged');
          $aboutPosts = new WP_Query(array(
            'post_type' => 'tour',
              'post_status' => 'publish',
              'posts_per_page' => 3,
          ));

          if ($aboutPosts->have_posts()) :
            while ($aboutPosts->have_posts()) :
              $aboutPosts->the_post();
              ?> 
        <span> <?php the_title(); ?> </span>
                  <br>

  <?php endwhile;
            echo paginate_links(array(
              'total' => $aboutPosts->max_num_pages
            ));

          endif;
   ?>   
</div>

FUNCTION.PHP

function tourcat_ajax_by_order() { if (isset($_REQUEST)) {
    $posts_per_page = et_get_option( 'divi_archivenum_posts' ) ;
        $args = array(              // WP query args
              'post_type' => 'tour',
              'post_status' => 'publish',
              'posts_per_page' => $posts_per_page
          );
     $tour_query = new WP_Query($args);
       if ( $tour_query->have_posts() ) {  // Have posts start here
        while ( $tour_query->have_posts() ) {   // While starts here
            $tour_query->the_post();
          ?>
                  <span> <?php the_title(); ?> </span>
                  <br>
          <?php}   
echo paginate_links(array(
              'total' => $aboutPosts->max_num_pages
            ));}  
            else {
            echo 'No results found';}
     wp_reset_postdata();}
           die();}

JS CODE

function tourcat_orderby_posts() {
         $.ajax({
                url: ajaxurl,
                data: {
                    'action':'tourcat_ajax_by_order',  
                },
                success: function(data) {
                    // This outputs the result of the ajax request 
                    $(".tour_parent_div").html(data);  
                },
                error: function(errorThrown) {}
            });}

This is not not implemented correctly, you can try the following:

PAGE.PHP

Use the same markup and call after adding a wrapper to the content:

<div class="site-content clearfix">
       <h1>Alex Blog</h1>
       <div id="page-posts-wrapper">
        <?php
          $ourCurrentPage = get_query_var('paged');
          $aboutPosts = new WP_Query(array(
            'post_type' => 'tour',
              'post_status' => 'publish',
              'posts_per_page' => 3,
          ));

          if ($aboutPosts->have_posts()) :
            while ($aboutPosts->have_posts()) :
              $aboutPosts->the_post();
              ?> 
        <span> <?php the_title(); ?> </span>
                  <br>

  <?php endwhile;
            echo paginate_links(array(
              'total' => $aboutPosts->max_num_pages
            ));

          endif;
   ?>   
       </div>
</div>

FUNCTION.PHP

Load js file and localize query data to use later for page generation:

function custom_assets_39828328() {
        // Correct the path and js file name before using.
        wp_enqueue_script( 'ajax-pagination',  get_stylesheet_directory_uri() . '/js/ajax-pagination.js', array(), '1.0', true );

        global $wp_query;
        wp_localize_script( 'ajax-pagination', 'ajaxpagination', array(
            'ajaxurl' => admin_url( 'admin-ajax.php' ),
            'query_vars' => json_encode( $wp_query->query )
        ));
}

add_action( 'wp_enqueue_scripts', 'custom_assets_39828328' );

Write the callback function that will be used when browsing the pages:

/**
 * AJAX Pagination function
 */
function my_ajax_pagination_72372732() {

    $query_vars = json_decode( stripslashes( $_POST['query_vars'] ), true );


    $query_vars['post_type'] = 'tour';
    $query_vars['paged'] = $_POST['page'];
    $query_vars['post_status'] = 'publish';
    $query_vars['posts_per_page'] = 3;


    $posts = new WP_Query( $query_vars );
    $GLOBALS['wp_query'] = $posts;


    if( ! $posts->have_posts() ) { 
        echo 'No results found';
    }
    else {
        while ( $posts->have_posts() ) { 
            $posts->the_post();
            ?>
                <span> <?php the_title(); ?> </span><br>      
            <?php

        }
            echo paginate_links(array('total' => $posts->max_num_pages  ));
    }

    die();
}
add_action( 'wp_ajax_nopriv_ajax_pagination', 'my_ajax_pagination_72372732' );
add_action( 'wp_ajax_ajax_pagination', 'my_ajax_pagination_72372732' );

JS Code

Pass the necessary details through Ajax to the call function and display response:

(function($) {
    function find_page_number(element) {
        element.find('span').remove();
        return parseInt(element.html());
    }
    $(document).on('click', 'a.page-numbers', function(event) {
        event.preventDefault();
        page = find_page_number($(this).clone());
        $.ajax({
            url: ajaxpagination.ajaxurl,
            type: 'post',
            data: {
                action: 'ajax_pagination',
                query_vars: ajaxpagination.query_vars,
                page: page
            },
            success: function(html) {
                $('#page-posts-wrapper').empty();
                $('#page-posts-wrapper').append(html);
            }
        })
    })
})(jQuery);

You can also replace the ajax callback query args with this (optional):

$new_args = array(
      'post_type' => 'post',
      'post_status' => 'publish',
      'paged' => $_POST['page'],
      'posts_per_page' => 3,
 );

Will work in both cases.

Seems you want to have the results using ajax without reloading the page, the following code might help : Hope this will work

paginate,js :

$('.pagi').on('click',function()
{   
    var pageid=$(this).data('page');
    var page_total=$(this).data('total');
    var data={
            action: "ajax_by_order",
            pageid: pageid,
            page_total:page_total
        };

    $.post(sitesettings.ajaxurl, data,function(res){
        var cont = JSON.parse(res);
        $('.result-content').html(cont.html);
        $('.pagin').html(cont.pagination_html);

    });
});

Function.php

function paginate_script() {
        // Correct the path and js file name before using.
        wp_enqueue_script( 'paginate',  get_stylesheet_directory_uri() . '/js/paginate.js', array(), '1.0', true );

        wp_localize_script( 'paginate', 'sitesettings', array(
            'ajaxurl' => admin_url( 'admin-ajax.php' ),
        ));
}

add_action( 'wp_enqueue_scripts', 'paginate_script' );

add_action('wp_ajax_nopriv_ajax_by_order', 'tristup_ajax_by_order' ); //witout logged in
add_action("wp_ajax_ajax_by_order","tristup_ajax_by_order");           //logged in

function tristup_ajax_by_order()
{
    $page_id=$_POST['page_id'];
    $page_total=$_POST['page_total'];

    $args['post_type']='tour';
    $args['post_status']='publish';
    $args['posts_per_page']=3;

    if($page_id>0)
    {
        $args['offset']=(3*$page_id);       
    }
    $aboutPosts = new WP_Query($args);

    $output='';
    $pagination_html='';
    if ( $aboutPosts->have_posts() ) 
    {
        while ( $aboutPosts->have_posts() ) : $aboutPosts->the_post();

            $output.='<div>'.get_the_title().'</div>';

        endwhile; 
    }

    for($i=0;$i<$page_total;$i++)
    {
        $j=$i+1;
        $pagination_html.='<span><a href="javascript:void(0);" class="pagi" data-page="'.$i.'" data-total="'.$page_total.'">'.$j.'</span>';
    }

    $result['html']=$flag;
    $result['pagination_html']=$pagination_html;

    echo json_encode($result);
    die();
}//end of function

Page.php

<div class="site-content clearfix">
       <h1>Alex Blog</h1>
        <?php
                $args['post_type']='tour';
                $args['post_status']='publish';
                $args['posts_per_page']=3;
                $aboutPosts = new WP_Query($args);
        ?>
        <div class="result-content">
        <?php 
                if ($aboutPosts->have_posts()) :
                    while ($aboutPosts->have_posts()) : $aboutPosts->the_post();
        ?> 
                <div> <?php the_title(); ?> </div>               

        <?php 
                    endwhile; 
                endif;          
        ?>   
        </div>
        <div class="pagin">
        <?php 
            for($i=0;$i<$aboutPosts->max_num_pages;$i++)
            {
                $j=$i+1;
        ?>
                <span><a href="javascript:void(0);" class="pagi" data-page="<?php echo $i; ?>" data-total="<?php echo $aboutPosts->max_num_pages; ?>"><?php echo $j; ?></span>
        <?php
            }
        ?>
        </div>
</div>