Ajax call from Plugin using Class
I'm making a plugin with a class and methods.
This class gets called through the theme ( hard coded ) to enqueue and localize my js. it also prepares it for ajax. However, i keep getting ERROR: 400
POST
http://www.devsite.local/wp-admin/admin-ajax.php
400 (Bad Request)
I've ran ajax outside of a class in multiple plugins and at the functions.php with no issues, but i can't get it to work inside a class.
This is my code:
class CCYTFeatured {
public function __construct(){
$this-cc_yt_scripts();
add_action( 'wp_enqueue_scripts', array($this, 'cc_yt_scripts' ));
add_action( 'wp_ajax_cc_yt_featured', array( $this, 'cc_yt_featured' ) );
add_action( 'wp_ajax_nopriv_cc_yt_featured', array( $this, 'cc_yt_featured' ) );
}
// Load CSS AND JAVA FRONT END
public function cc_yt_scripts() {
wp_register_style( 'cc_yt_style',
plugins_url( '/css/cc_yt.css', __FILE__ ),
array(),
cc_yt_version()
);
wp_enqueue_style('cc_yt_style');
// JAVASCRIPT
wp_register_script( 'cc_yt_javascript',
plugins_url( '/js/cc_yt.js', __FILE__ ),
array('jquery'),
cc_yt_version(),
true
);
wp_enqueue_script('cc_yt_javascript');
wp_localize_script(
'cc_yt_javascript',
'cc_yt_script',
array(
'ajaxurl' = admin_url( 'admin-ajax.php' , __FILE__ ),
'ajax_nonce' = wp_create_nonce('my_nonce'),
)
);
}
public function cc_yt_featured(){
check_ajax_referer( 'my_nonce', 'security' );
echo json_encode('IM HERE, YOU CAN FIND US');
}
}
This is my JavaScript ajax call:
jQuery.ajax({
url: cc_yt_script.ajaxurl,
type : 'POST',
data: {
action : 'cc_yt_featured',
security: cc_yt_script.ajax_nonce,
post: 'bananas',
},
success: function(response) {
console.log('THIS IS THE RESPONSE: '+ response);
}
});
I keep getting the same error, i can't figure out what is wrong with my class:
This is how i call it.
$cc_yt = new CCYTFeatured;
I have that call hard coded inside a theme file. This does enqueue the styles and scripts successfully.
The ajax get is the following:
http://www.devsite.local/wp-admin/admin-ajax.php?action=cc_yt_featuredsecurity=79e39910b8post=bananas
Anyone have any clue what i'm doing wrong??
Thanks!
Topic ajax Wordpress javascript
Category Web