I've tried a bunch of different things but I just cannot get AJAX with Wordpress to work. I clearly don't get something but I do not know what it is. The PHP function works fine since I have tested it, it just seemingly isnt getting through to the JS. The idea is that when someone clicks the #subscribe-btn div its updates that users meta, nothing overly sophisticated. Any help on why this isnt working would be great.
This is in my theme's functions.php:
function add_admin_ajax()
{
wp_localize_script( 'add_ajax', 'functionAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'add_ajax', get_template_directory_uri().'/assets/js/onLoad.js', 'jquery', true);
}
add_action('template_redirect', 'add_admin_ajax');
add_action( 'wp_ajax_subscribe_cat', 'subscribe_cat' );
add_action( 'wp_ajax_nopriv_subscribe_cat', 'subscribe_cat' );
function subscribe_cat()
{
global $current_user;
if(is_user_logged_in())
{
get_currentuserinfo();
$userid = $current_user->ID;
$catsub = get_category(get_query_var('cat'));
$cat_id = $catsub->cat_ID;
$subs = get_user_meta($userid, 'user_subscriptions', true);
if(empty($subs))
{
$subs = array();
}
if(!in_array($cat_id, $subs))
{
$subs[] = $cat_id;
update_user_meta($userid, 'user_subscriptions', $subs);
//echo json_encode($subs);
}
}
die();
}
And then the jQuery:
$(document).on("click", "#subscribe-btn", function (e) {
//e.preventDefault();
$('#subscribe-btn').fadeOut(300);
$.ajax({
url: ajaxurl,
data: {action: "subscribe_cat"},
success: function() {
alert("Yay!")
},
error: function() {
alert("BOo!")
}
}); // end ajax call
});
I'm not getting either the success or error message. The div does fade out though that is something i guess. Any help here? Thanks!
EDIT: I just changed the action identifier in add_action from subscribe to subscribe_cat and changed the ajax url from functionAjax.ajaxurl to simply ajaxurl. Now its responding. However I get the success alert twice, which I do not understand, and it doesn't seem its actually triggering the PHP function, or at least not properly, since I'm not getting the results I get when I simply call the function in PHP whithout ajax. Any ideas here?