I've looked at a heap of other people with this same problem but I still can't find a solution. Hopefully someone can see what I've missed because I'm about to pull my hair out.
My ajax call is not getting to the response function.
This is how my code is called. This function gets called from a template.
function build_a_boat(){
// blah blah blah
require_once BUILDNEWBOAT_PATH . 'includes/BuildNewBoatPlugin.php';
$build_boat_plugin = new BuildNewBoatPlugin();
$build_boat_plugin->run();
}
The below code is inside by plugin class. When I click a radio button, I receive the "javascript is working" alert, then an admin-ajax.php 400 error in the console.
I think my problem is that the ajax return hook isn't firing (wp_ajax_post_new_boat_form).
If I move my code out of the plugin class, everything works.
public function __construct() {
// other stuff happens here
$this->init_plugin();
add_action( 'wp_enqueue_scripts', array( $this, 'init_plugin' ) );
add_action( 'wp_ajax_post_new_boat_form', array($this,'next_step_ajax' ));
add_action( 'wp_ajax_nopriv_post_new_boat_form', array($this,'next_step_ajax' ));
}
function init_plugin() {
wp_register_script( 'new_boat_form_script', plugin_dir_url( __FILE__ ) . 'js/new_boat_form.js', array() );
wp_enqueue_script( 'new_boat_form_script');
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' )
)
);
}
public function next_step_ajax(){
print "It worked. Moving to the next step<br>";
die();
}
My javascript is this
$(function () {
$("#boatFormStep input[type=\"radio\"]").on("change",function(){
alert("javascript is working");
$.ajax({
url: new_boat_form_script_ajax_object.ajax_url,
data: {
action: 'post_new_boat_form'
},
method: 'POST',
success: function (response) {
console.log(response)
$("#boatFormStep").html(response);
},
error: function (error) {
console.log(error)
}
})
})
});
Help!