I have read other questions regarding the same issue but nothing seems to help in my case. Maybe someone sees something in my code that I cannot see?
I created a plugin with a class, then I have an AJAX call that triggers when I click on a HTML element on the page. All seems to work, except that it doesn't enter the callback inside the plugin.
plugin.php
class BSPFPluginClass {
protected $nonce = 'mynonce';
public function __construct() {
/** other actions here ... */
add_action( 'wp_enqueue_scripts', array( $this, 'myinit' ) );
add_action( 'wp_ajax_myajaxcall', array( $this, 'myajaxcall' ) ); // executed when logged in
add_action( 'wp_ajax_nopriv_myajaxcall', array( $this, 'bspf_ajax_voting' ) ); // executed when logged out
}
public function myinit() {
// Register the script
wp_register_script( 'plugin-js', plugins_url( 'js/plugin.js', __FILE__ ), array() );
if (is_page('somepage')) {
// Enqueued script with localized data.
wp_enqueue_script( 'plugin-js' );
// Localize the script with new data
wp_localize_script( 'plugin-js', 'plugin_ajax', [
'ajax_url' => plugins_url( 'plugin.php', __FILE__ ),
'nonce' => wp_create_nonce( $this->nonce ),
]);
}
}
public function myajaxcall() {
check_ajax_referer( $this->nonce );
if (true) {
echo 'Yes it works!';
}
else {
echo 'No it does not work!';
}
wp_die(); // stop executing script
}
}
Then, js/plugin.js
jQuery(document).ready(function($) {
$(".myclass").click(function() {
$.post(plugin_ajax.ajax_url, {
_ajax_nonce: plugin_ajax.nonce,
action: 'myajaxcall'
}, function(response) {
console.log('SUCCESS: '+response);
}).done(function() {
console.log('DONE');
}).fail(function() {
console.log('ERROR');
}).always(function() {
console.log('ALWAYS');
});
});
});
When I hit the HTML element with the trigger class everything goes well and I get the following on the console:
SUCCESS: DONE ALWAYS
So it is like everything is correct, except is not entering the action 'myajaxcall'.
Any leads?
Thank you in advance.
ajax_url
should beadmin_url( 'admin-ajax.php' )
and notplugins_url( 'plugin.php', __FILE__ )