Reputation: 11
I have a strange and frustrating behaviour of wordpress admin-ajax.php file, when i make an ajax request it returns 400 error bad request.
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; ?>';
jQuery(function($){
$('#true_loadmore').click(function(){
$(this).text('Loading...');
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('View more recent Posts').before(data);
current_page++;
if (current_page == max_pages) $("#true_loadmore").remove();
} else {
$('#true_loadmore').remove();
}
}
});
});
});
my functions.php .
add_action('wp_ajax_loadmore', 'true_load_posts');
add_action('wp_ajax_nopriv_loadmore', 'true_load_posts');
function true_load_posts(){
$args = unserialize( stripslashes( $_POST['query'] ) );
$args['paged'] = $_POST['page'] + 1;
$args['post_status'] = 'publish';
query_posts( $args );
if( have_posts() ) :
while( have_posts() ): the_post();
get_template_part( 'template-parts/post/content', get_post_format() );
endwhile;
endif;
die();
}
And I got 400 error . Someone could help me to please? thank you.
Upvotes: 1
Views: 752
Reputation:
the problem should be the action in your sending data.
The 'action' value must correspond to the function name in the php side (and in the add_action method ).
var data = {
'action': 'true_load_posts', //instead of 'loadmore'
'query': true_posts,
'page' : current_page
};
Hope this help.
Upvotes: 1