I have built a plugin and I need to use ajax in the admin and have followed the documentation here: https://codex.wordpress.org/AJAX_in_Plugins
However, the response I keep getting is 0.
I know there are many posts with the same issue and I have been through them all but cannot find the solution for me. Please help.
I use a class for the plugin and have the jquery in a seperate file.
myplugin-admin.js
function getFeatureIDs(selectObject){
var value = selectObject.value;
console.log(value);
console.log(ajax_object.we_value);
console.log(ajax_object.ajax_url);
var data = {
'action': 'get_etim',
'whatever': ajax_object.we_value
};
jQuery.post(ajax_object.ajax_url, data, function(response) {
alert('Got this from the server: ' + response);
});
}
class-myplugin-admin.php
class myplugin_Admin {
private $myplugin;
private $version;
public function __construct($myplugin,$version ) {
add_action('wp_ajax_get_etim', 'get_etim');
add_action( 'wp_ajax_nopriv_get_etim', 'get_etim' );
}
public function enqueue_scripts() {
wp_enqueue_script( $this->myplugin, plugin_dir_url( __FILE__ ) . 'js/myplugin-admin.js', array( 'jquery' ), $this->version, false );
wp_localize_script( $this->myplugin, 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
}
public function get_etim() {
echo $_REQUEST['whatever'];
wp_die();
}
}
Results in console:
EC003025
1234
https://mytestsite.plesk.page/wp-admin/admin-ajax.php
Alert is always,
"Got this from the server: 0"
which suggests the action function is not being called.
Please, what am I missing?
Thanks
register_rest_route
. Also the Codex is very old and contains out of date information. You should be using the developer hub instead