This question already has an answer here:
- Wordpress admin-ajax.php 404 bad request 2 answers
I'm working on a search plugin for the front-end of a Wordpress site. At the moment I keep getting a 400 Bad Request Error and I can't understand why. I've reviewed many questions on SO and the WordpressStackExchange but cannot see where I'm going wrong, nothing appears to be out of place. Please give me guidance:
plugin.php:
function my_admin_scripts() {
$localize = array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
);
wp_register_script('veh-app-search', plugin_dir_url( __FILE__ ) . '/ajax.js', '', '', true);
wp_localize_script( 'veh-app-search', 'veh_app_script', $localize);
wp_enqueue_script( 'veh-app-search', plugin_dir_url( __FILE__ ) . '/ajax.js', array( 'jquery' ) );
}
add_action( 'wp_enqueue_scripts', 'my_admin_scripts' );
add_action( 'wp_ajax_the_ajax_hook', 'handle_request' );
add_action( 'wp_ajax_nopriv_the_ajax_hook', 'handle_request' );
//takes care of the $_POST data
function handle_request(){
echo "hello";
}
ajax.js
var data = {
action: 'handle_request',
RequestType: 'category',
Category: jQuery('#Category option:selected').val()
};
jQuery.post(
veh_app_script.ajaxurl,
data,
function(categories){
console.log(categories);
}
);
One would expect to see "Hello" in the console but I only see the error in the console:
jquery.js?ver=1.12.4:4 POST http://localhost/wp-admin/admin-ajax.php 400 (Bad Request)