$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>php - AJAX pagination, update current page|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

php - AJAX pagination, update current page

matteradmin9PV0评论

I created a numeric pagination that loads the posts via AJAX.

This is the PHP and jQuery code:

// PHP Code
function ajax_pagination_enqueue_scripts() {
    wp_enqueue_script( 'ajax-pagination',  get_stylesheet_directory_uri() . '/js/ajax-pagination.js', array( 'jquery' ), '1.0', true );
    wp_localize_script( 'ajax-pagination', 'ajax_pagination_vars', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'query_vars' => json_encode( $wp_query->query )
    ));
}

add_action( 'wp_enqueue_scripts', 'ajax_pagination_enqueue_scripts' );

function ajax_pagination_load() {
    $query_vars = json_decode( stripslashes( $_POST['query_vars'] ), true );
    $query_vars['paged'] = $_POST['page'];
    $posts = new WP_Query( $query_vars );
    $GLOBALS['wp_query'] = $posts;
    if( $posts->have_posts() ) :
        while( $posts->have_posts() : $posts->the_post() ) :
            get_template_part( 'content', get_post_format() );
        endwhile;
    else:
        get_template_part( 'content', 'none' );
    endif;
    die();
}

add_action( 'wp_ajax_nopriv_ajax_pagination', 'ajax_pagination_load' );
add_action( 'wp_ajax_ajax_pagination', 'ajax_pagination_load' );

// jQuery Code
(function($) {
    $(document).on( 'click', '.nav-button a', function( event ) {
        event.preventDefault();
        var page = $(this).data('page');
        $.ajax({
            url: ajax_pagination_vars.ajaxurl,
            type: 'post',
            data: {
                action: 'ajax_pagination',
                query_vars: ajax_pagination_vars.query_vars,
                page: page
            },
            success: function( response ) {
                $('.main-content').html(response);
            }
        })
    })
})(jQuery);

The code works, but when I refresh the page the posts are loaded again from the first page.

Ex: If I click the button that loads the page 2 when I refresh the page the posts are displayed from the page 1.

There is a way to remain on the same page even after the page refresh?

Thanks.

I created a numeric pagination that loads the posts via AJAX.

This is the PHP and jQuery code:

// PHP Code
function ajax_pagination_enqueue_scripts() {
    wp_enqueue_script( 'ajax-pagination',  get_stylesheet_directory_uri() . '/js/ajax-pagination.js', array( 'jquery' ), '1.0', true );
    wp_localize_script( 'ajax-pagination', 'ajax_pagination_vars', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'query_vars' => json_encode( $wp_query->query )
    ));
}

add_action( 'wp_enqueue_scripts', 'ajax_pagination_enqueue_scripts' );

function ajax_pagination_load() {
    $query_vars = json_decode( stripslashes( $_POST['query_vars'] ), true );
    $query_vars['paged'] = $_POST['page'];
    $posts = new WP_Query( $query_vars );
    $GLOBALS['wp_query'] = $posts;
    if( $posts->have_posts() ) :
        while( $posts->have_posts() : $posts->the_post() ) :
            get_template_part( 'content', get_post_format() );
        endwhile;
    else:
        get_template_part( 'content', 'none' );
    endif;
    die();
}

add_action( 'wp_ajax_nopriv_ajax_pagination', 'ajax_pagination_load' );
add_action( 'wp_ajax_ajax_pagination', 'ajax_pagination_load' );

// jQuery Code
(function($) {
    $(document).on( 'click', '.nav-button a', function( event ) {
        event.preventDefault();
        var page = $(this).data('page');
        $.ajax({
            url: ajax_pagination_vars.ajaxurl,
            type: 'post',
            data: {
                action: 'ajax_pagination',
                query_vars: ajax_pagination_vars.query_vars,
                page: page
            },
            success: function( response ) {
                $('.main-content').html(response);
            }
        })
    })
})(jQuery);

The code works, but when I refresh the page the posts are loaded again from the first page.

Ex: If I click the button that loads the page 2 when I refresh the page the posts are displayed from the page 1.

There is a way to remain on the same page even after the page refresh?

Thanks.

Share Improve this question asked Nov 5, 2018 at 16:13 level7level7 252 silver badges4 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

When you refresh the page, there is currently no state you can use to know you're on page 2.

You could use the History API to update the page URL without refreshing the page:

history.pushState(data, title, 'https://yourpage/?page=2');

You can also set some state on the user browser using the SessionStorage instead of the LocalStorage API, because the session will not persist when the user closes the browser tab:

// Store current page
sessionStorage.setItem('page', 2);

// Get current page on page load/refresh
var currentPage = sessionStorage.getItem('page');

This second method has its issues since the user can go to a different page and then get back to the paginated page and get the second page of results, instead of getting the first one, so you need to be careful about this approach.

You can set a cookie or local storage to set the current page, as there is no way to track the paged variable you pass with ajax on page reload. Update js code to check for cookie or local storage on page reload and get result based on that.On your ajax success function set localstorage like this.

// Store current page number
localStorage.setItem('page', 2);

And on page reload check local storage

//Get current page number
var currentPage = localStorage.getItem('page');

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far