Here’s what I try to do : calling a function in my theme functions.php from the front of my theme.
So, on the front :
$(document).on('click','.btn-vote',function(e){
e.preventDefault();
var $that = jQuery(this);
var id = $that.attr('data-id');
var data = {
'action': 'voteIncrementer',
'id': id
};
jQuery.post(ajaxurl, data,function(response){ // ajaxurl is defined in footer.php > var ajaxurl="<?php echo admin_url("admin-ajax.php'); ?>';
console.log(response);
$that.find('.vote-count').html(response);
});
});
And the related function in functions.php :
add_action("wp_ajax_voteIncrement", "voteIncrement");
add_action("wp_ajax_nopriv_voteIncrement", "voteIncrement");
function voteIncrement(){
echo 'hello';
die();
}
Quit simple right ? But the thing is : in my JS, the log returns 0 (that means that wp-ajax can’t find my function).
What I am missing ?
1 Answer
I think that your problem is ajaxurl
is not available for your script. Try to defined that varibale before your js code is loaded. The best way is using wp_localize_script:
The PHP:
add_action( 'wp_enqueue_scripts', 'cyb_enqueue_scripts' );
function cyb_enqueue_scripts() {
//Change the key and url with yours
wp_register_script('my-js', get_stylesheet_directory_uri(). '/js/my-js.js', array( 'jquery' ) );
wp_enqueue_script('my-js');
//Localize script data to be used in my-js.js
$scriptData = array();
$scriptData['ajaxurl'] = admin_url( 'admin-ajax.php' );
$scriptData['action'] = 'voteIncrement';
wp_localize_script( 'my-js', 'my_js_data', $scriptData );
}
add_action("wp_ajax_voteIncrement", "voteIncrement");
add_action("wp_ajax_nopriv_voteIncrement", "voteIncrement");
function voteIncrement(){
echo 'hello';
die();
}
The js:
(function($){
$(document).ready(function(){
$('.btn-vote').on('click',function(e){
e.preventDefault();
var $that = jQuery(this);
var id = $that.attr('data-id');
var data = {
'action': my_js_data.action,
'id': id
};
jQuery.post( my_js_data.ajaxurl, data, function(response) {
console.log(response);
$that.find('.vote-count').html(response);
});
});
});
})(jQuery);
Also, I would change the post method in the ajax request for get. It is faster than post and your case seems not to need a post request.