Custom plugin giving: wp-admin/admin-ajax.php 400 (Bad Request)

I am having trouble debugging an issue with a plugin that I’m writing. I want to do an Ajax request when a user changes the option on a select input. The thing is it was fully working as expected yesterday, then when I test the website today (no code changes were made at all since yesterday) I’m getting an:

domain.com/wp-admin/admin-ajax.php 400 (Bad Request)

message in my Chrome console. If I try in Internet Explorer/FireFox it doesn’t give the error in console but the Ajax request is still not working.

The plugin I’m creating is on a DigitalOcean droplet which was made using their one click app for WordPress.

Here is the barebones code I’m using on the plugin for the ajax:

//This is in a class’ constructor method
add_action(‘wp_enqueue_scripts’, array($this, ‘plugin_prefix_scripts’));

//PLUGIN_URL is a constant created earlier in the plugin
public function plugin_prefix_scripts() {
wp_enqueue_script(‘plugin_prefix_scripts’, PLUGIN_URL . ‘scripts/frontend_script.js’);
wp_localize_script(‘plugin_prefix_scripts’, ‘js_object’,
array(
‘ajax_url’ => admin_url(‘admin-ajax.php’)
)
);

}

frontend_script.js:

$(‘#plugin-prefix-option-one, #plugin-prefix-option-two’).on(‘change’, function() {
var data = {
‘action’: ‘plugin_prefix_page_change’,
‘option_val’: ‘some_val’,
}

$.post(js_object.ajax_url, data, function(response) {
console.log(response);
});

Back in the class:

add_action(‘wp_ajax_plugin_prefix_page_change’, array($this, ‘plugin_prefix_page_change’));

public function plugin_prefix_page_change() {
$arr = array(1, 2, 3, 4, 5);

wp_send_json($arr);

//I’ve also tried wp_die() and no die call at all but same outcome
die();
}

I’m unsure how to debug this further. Any help is much appreciated.

Thanks

Read more here:: Custom plugin giving: wp-admin/admin-ajax.php 400 (Bad Request)

Leave a Reply

Your email address will not be published. Required fields are marked *