Ajax 400 error when used inside a plugin
I'm really, really stuck. When I run this code I get a checkbox displayed. When I click the checkbox, the javascript is run. I get test in the console, followed by a 400 POST error. I can get this to work perfectly if I take it out of the plugin (and remove $this from the ajax actions), but I don't want to do that. Please can someone point me in the right direction!
This is the code from my plugin root file
require_once BUILDNEWBOAT_PATH . 'includes/BuildNewBoatPlugin.php';
$build_boat_plugin = new BuildNewBoatPlugin();
$build_boat_plugin-run();
This is inside the BuildNewBoatPlugin class
public function __construct() {
add_action( 'wp_enqueue_scripts', array( $this, 'init_plugin' ) );
add_action( 'wp_ajax_post_new_boat_form', array( $this, 'post_new_boat_form' ));
add_action( 'wp_ajax_nopriv_post_new_boat_form', array( $this, 'post_new_boat_form' ));
}
public function init_plugin() {
wp_register_script( 'new_boat_form_script', plugin_dir_url( __FILE__ ) . 'js/new_boat_form.js', array() );
wp_localize_script( 'new_boat_form_script', 'new_boat_form_script_ajax_object',
array(
'ajax_url' = admin_url( 'admin-ajax.php' ),
//'ajax_nonce' = wp_create_nonce( 'new_boat_form_ajax_nonce' )
)
);
wp_enqueue_script( 'new_boat_form_script');
}
public function post_new_boat_form(){
print_r($_POST);
?
pTesting AJAX/p
?php
die();
}
public function run(){
// displays an html form
}
And this is my javascript file
$(#boatFormStep input[type=\radio\]).on(change,function(){
console.log(test);
$.ajax({
url: new_boat_form_script_ajax_object.ajax_url,
data: {
action: 'post_new_boat_form'
},
method: 'POST',
success: function (response) {
console.log(test+response)
$(#boatFormStep).html(response);
},
error: function (error) {
console.log(error)
}
})
})
});