So I have limited experience with Ajax and I'm not entirely sure how to debug/resolve the issue. The error in question is;
admin-ajax.php - 400 Bad Request (xhr).
I have checked the resource loaded and I can get a response of '0'. Looking into it I can see that a '0' response means either that the action is not set (in the ajax data) or that the action's callback function cannot be found.
Seeing as I have set an action I can only assume this is because the call back function cannot be found. But checking the code theres no typos in the callbacks?
Any help I could get would be much appreciated.
functions.php
add_action('wp_head', function(){
require_once( get_stylesheet_directory() .'/inc/better-comments.php' );
require( get_stylesheet_directory() .'/inc/ajax.php' );
});
ajax.php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
add_action('wp_ajax_nopriv_front_load_more', 'front_load_more');
add_action('wp_ajax_front_load_more', 'front_load_more');
function front_load_more() {
global $post;
$post = get_post( $_POST['post_id'] );
setup_postdata( $post );
wp_list_comments( array( 'callback' => 'better_comments' ) );
die();
};
theme.js
jQuery(document).ready(function($){
$(document).on('click', '.front-load-more', function(){
var button = $(this);
// decrease the current comment page value
cpage--;
$.ajax({
url : ajaxurl, // AJAX handler, declared before
data : {
'action' : 'front_load_more',
'post_id': parent_post_id, // the current post
'cpage' : cpage, // current comment page
},
type : 'POST',
beforeSend : function ( xhr ) {
button.text('Loading...'); // preloader here
},
success : function( data ){
if( data ) {
$('ol.comment-list').append( data );
button.text('More comments');
// if the last page, remove the button
if ( cpage == 1 )
button.remove();
} else {
button.remove();
}
}
});
return false;
});
});
comments.php (the trigger)
<?php
$cpage = get_query_var('cpage') ? get_query_var('cpage') : 1;
if( $cpage > 1 ) {
echo '<a class="btn btn-block btn-soft-primary transition-3d-hover front-load-more">Load More</a>
<script>
var ajaxurl = \'' . admin_url('admin-ajax.php') . '\',
parent_post_id = ' . get_the_ID() . ',
cpage = ' . $cpage . '
</script>';
}
?>
Amended - add_action('wp_ajax_nopriv_front_load_more', 'front_load_more');
Amended - add_action('wp_ajax_front_load_more', 'front_load_more');
EDIT: 21 Jan 15:23 As @cabrerahector said, I had code within my ajax.php file that needed to be moved to my functions.php file. This resolved the bad request issue.
front-load-moreandfront_load_more. Stick to underscores. Also, are you sure you want to use the admin-url? Does the feature require the user to be a logged in admin?add_action('wp_ajax_nopriv_front-load-more', 'front-load-more');assigned so I thought that would negate the issue.ajax.phpshould be infunctions.phpinstead.parent_post_idhasn't been initialized anywhere.