All AJAX requests return a 400 error

I have not tested your code, but one problem I noticed is the contentType property in your $.ajax() call: contentType: ‘application/json; charset=utf-8’, because that way, (from the PHP side) the action (i.e. ajax_load_more) is not available in $_REQUEST[‘action’] which WordPress uses to determine the AJAX action being called, and when the action is not known, … Read more

AJAX and -1 response

You should end all “async” functions with die() or exit, otherwise WordPress does it for you returning -1.

Pagination Using ajax

I had got the ans. First you have to add following code in your function.php to call ajax in your template** add_action( ‘wp_ajax_demo-pagination-load-posts’, ‘cvf_demo_pagination_load_posts’ ); add_action( ‘wp_ajax_nopriv_demo-pagination-load-posts’, ‘cvf_demo_pagination_load_posts’ ); function cvf_demo_pagination_load_posts() { global $wpdb; // Set default variables $msg = ”; if(isset($_POST[‘page’])){ // Sanitize the received page $page = sanitize_text_field($_POST[‘page’]); $cur_page = $page; $page -= … Read more

Ajax Request for both logged and non logged users

You can add the function to both hooks: add_action(‘wp_ajax_ajaxTest’, ‘ajaxTest’); add_action(‘wp_ajax_nopriv_ajaxTest’, ‘ajaxTest’); But, there’s a better way to do it, use a REST API endpoint: add_action( ‘rest_api_init’, function () { register_rest_route( ‘yourstuff/v1’, ‘/test/’, array( ‘methods’ => ‘POST’, ‘callback’ => ‘yourstuff_test_endpoint’ ) ); } ); function yourstuff_test_endpoint( $request ) { $stuff = $request[‘stuff’]; return “Received “.esc_html( … Read more

Bad request 400 from custom ajax call

There’s only one reason you get a 400 error with admin-ajax.php: The wp_ajax_{$action} or wp_ajax_nopriv_{$action} action has not been hooked with an {$action} that matches the action data parameter sent with your request. So either your callback is not hooked, or you’re not sending the action correctly. Your code is making both errors. You are … Read more