0
votes

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?

2
consolelog functionAjax.ajaxurl ... it may be wrong. - David
So I did try now just changing it to ajaxurl and that worked! I got the "yay!" alert. So that is a step forward. The thing is now I do get the alert twice? And also it doesnt seem the actual function is executing. Thoughts? - arian1123
you have 2 alerts above, one runs on success one on fail. I see you have commented out preventDefault() also, if you have a button here it may actually submit the code. You possibly have a problem with get_query_var above, i'm not sure if it reads correctly from the ajax file, try echoing out the result (put a variable inside the function argument for success and console.log this. - David
Ok so I worked on it so that i can verify that the function is being executed. The problem is now that the PHP is not executing properly in ajax. Could have something to do with what you are saying. If I try echoing a response from inside the if statements its empty. But if I echo at the end of the function I get the output when using function(response) in jquery. The issue seems to lie in ajax. Ideas on how to fix this? - arian1123
So I did test and I replaced $cat_id with a constant. I commented out the lines with get_query_var and set $cat_id to 77. Everything worked perfectly so you were right that get_query_var is a problem. Do you have any idea how to workaround this? - arian1123

2 Answers

1
votes

One thing for sure you need to do is change the way your action is setup in the WordPress themes functions.php file.

I think this is an issue: wp_ajax_subscribe

This:

add_action( 'wp_ajax_subscribe', 'subscribe_cat' );    
add_action( 'wp_ajax_nopriv_subscribe', 'subscribe_cat' );

should be:

add_action( 'wp_ajax_subscribe_cat', 'subscribe_cat' );    
add_action( 'wp_ajax_nopriv_subscribe_cat', 'subscribe_cat' );

The action you set in your javascript needs to match the ending of the first parameter in your wordpress add_action call.

The WordPress documentation

0
votes

You should pass page info such as query_var as "data" with your ajax function.

frontend page

<?php

$catsub = get_category(get_query_var('cat'));
$cat_id = $catsub->cat_ID;
?>


<script>
    $(document).on("click", "#subscribe-btn", function (e) {
        e.preventDefault();
        $('#subscribe-btn').fadeOut(300);

        $.ajax({
          url: ajaxurl,
          data: {
                action: "subscribe_cat",
                catid: "<?php echo $cat_id;?>"
          },
          success: function(response) {
                console.log(response);
         },
         error: function() {
            alert("BOo!")
         }

         }); // end ajax call

    });
</script>

Also in your ajax function you had a condition that will always evaluate to false.

functions.php

add_action( 'wp_ajax_subscribe_cat', 'subscribe_cat' );    
add_action( 'wp_ajax_nopriv_subscribe_cat', 'subscribe_cat' );

function subscribe_cat(){



    //changed here!!
    $cat_id = $_POST['catid'];

    if(!$cat_id){
        echo 'cat_id is missing';   
        exit;
    } elseif(!is_user_logged_in()) {
        echo 'Not logged in!';  
        exit;
    }   

    $userid = get_current_user_id();


    $subs = get_user_meta($userid, 'user_subscriptions', true);

    if(empty($subs))
        $subs = array();

    $subs[] = $cat_id;
    update_user_meta($userid, 'user_subscriptions', $subs); 
    echo json_encode($subs);
    exit;

}