简体   繁体   中英

AJAX handler throws 400 (Bad request) - why?

I am trying to apply a "Load more posts" function to a post loop, but I am dealing with a 400 Bad request, when admin-ajax.php is referred to.

The reference I used is this - https://rudrastyh.com/wordpress/load-more-posts-ajax.html

Following function (in functions.php) is passing query parameters to javascript:

function wordpress_my_load_more_scripts() 
{
    global $wp_query; 

    wp_enqueue_script('jquery');

    wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/myloadmore.js', array('jquery') );

    wp_localize_script( 'my_loadmore', 'wordpress_loadmore_params', array(
        'ajaxurl' => admin_url() . 'admin-ajax.php', 
        'posts' => json_encode( $wp_query->query_vars ), 
        'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
        'max_page' => $wp_query->max_num_pages
    ) );

    wp_enqueue_script( 'my_loadmore' );
}

add_action( 'wp_enqueue_scripts', 'wordpress_my_load_more_scripts' );

Parameters are passed to following jQuery script named "myloadmore.js":

jQuery(function($){
    $('.wordpress_loadmore').click(function()
    { 
        var button = $(this),
            data = {
            'action': 'loadmore',
            'query': wordpress_loadmore_params.posts, 
            'page' : wordpress_loadmore_params.current_page
        };

        console.log(wordpress_loadmore_params.ajaxurl);

        $.ajax({
            url : wordpress_loadmore_params.ajaxurl, // AJAX handler
            data : data,
            type : 'POST',
            beforeSend : function ( xhr ) 
            {
                button.text('Loading...'); 
            },
            success : function( data ){
                if( data ) { 
                    button.text( 'More posts' ).prev().before(data); 
                    wordpress_loadmore_params.current_page++;

                    if ( wordpress_loadmore_params.current_page == wordpress_loadmore_params.max_page ) 
                        button.remove(); // if last page, remove the button

                } else {
                    button.remove(); // if no data, remove the button as well
                }
            }
        });
    });
});

Following function inside functions.php is expected to provide three more posts inside while loop:

function wordpress_loadmore_ajax_handler()
    {
        $args = json_decode( stripslashes( $_POST['query'] ), true );
        $args['paged'] = $_POST['page'] + 1; 
        $args['post_status'] = 'publish';

        query_posts( $args );

        if(have_posts() ) :

            echo "We have post(s)!";

            while( have_posts() ): the_post();

                echo "A post!";

            endwhile;

        endif;

        die; 
    } 

    add_action('wp_ajax_loadmore', 'wordpress_loadmore_ajax_handler'); 
    add_action('wp_ajax_nopriv_loadmore', 'wordpress_loadmore_ajax_handler');

The post loop is this:

<ul class="products columns-3">

                    <?php 

                    $query_params = array(
                            'post_type' => 'post',
                            'posts_per_page' => 3
                    );

                    $wp_query = new WP_Query( $query_params);        

                    if( $wp_query->have_posts() ) :

                        while ($wp_query->have_posts()) : $wp_query->the_post(); ?>

                            <li class="product post-item">
                                <span class="post-image">
                                    <a href="<?php the_permalink(); ?>">
                                        <?php 
                                            if ( has_post_thumbnail()) 
                                            {
                                                the_post_thumbnail();
                                            }
                                        ?>
                                    </a>
                                </span>
                                <h2 class="post-title"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2>
                                <span class="post-category"><?php the_category(', ');?></span>
                            </li>

                        <?php endwhile; ?>

                    <?php endif; ?>

                </ul>

                <nav>
                    <?php

                    global $wp_query; // you can remove this line if everything works for you

                    // don't display the button if there are not enough posts
                    if (  $wp_query->max_num_pages > 1 )
                        echo '
                            <div class="wordpress_wrapper">
                                <div class="wordpress_loadmore">More posts</div>
                            </div>'; // you can use <a> as well
                    ?>
                </nav>

                <?php wp_reset_postdata(); ?>

Clicking the button to load more posts results in following message:

https://www.uvjagtpro.dk/wp-admin/admin-ajax.php
jquery.js?ver=1.12.4:4 POST https://www.uvjagtpro.dk/wp-admin/admin-ajax.php 400 ()
send @ jquery.js?ver=1.12.4:4
ajax @ jquery.js?ver=1.12.4:4
(anonymous) @ myloadmore.js:13
dispatch @ jquery.js?ver=1.12.4:3
r.handle @ jquery.js?ver=1.12.4:3

Why can't I parse variable in Array named "wordpress_loadmore_params.ajaxurl" without it causing a 400 bad request?

Link to page is here - https://www.uvjagtpro.dk/arkiv/

There are only 3 cases where WordPress will return a 400 on an AJAX request to

.../wp-admin/admin-ajax.php

  1. $_REQUEST['action'] variable is empty
  2. has_action( 'wp_ajax_' . $_REQUEST['action'] ) is false
  3. has_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] ) is false

So, you should verify that your code

add_action('wp_ajax_loadmore', 'wordpress_loadmore_ajax_handler'); 
add_action('wp_ajax_nopriv_loadmore', 'wordpress_loadmore_ajax_handler');

is really executed and the query does contain a $_REQUEST['action'] with contents 'loadmore'. This is easiest to do if you know how to use a PHP debugger otherwise I would use error_log() to display relevant messages after the add_actio n statements. You can also display the value of the has_action() functions.

Your code looks correct to me so I think the error is not the code itself but maybe its location.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM