4

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/

1 Answer 1

0

in your html add

 `<input name="action" type="hidden" value="test_function"/>` 

here "value" is your "action_name". Your ajax call is incorect. Data should be

url: "your php action script"
data: $(html data).serialize(),

About ajax first try to create ajax on your computer without wordpress. When you understand how ajax work try on Wordpress.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.