0

I want to perform some actions when ajax tasks done successfully. For instance, if the item added to the cart, I want to send an email. Also may perform a few more actions.

Setting up do_action('prefix_item_added_to_cart', $args); doesn't recognized and so add_action doesn't perform a task, in my case sending email.

If I write code procedural code to send an email, that works fine but using do_action.

Does not work

// ajax callback function
function my_ajax_callback() {

    ...
    // add item to cart
    $cart =. new Cart();
    $cart_id = $cart->add_item($params);

    // if item added successfully
    if($cart_id){
        // perform action
        do_action('prefix_item_added_to_cart', $args);
    }
    ...

}

// action callback
function send_email_to_user($args) {

    // send email notification
    wp_mail('set params for email');

}

// action
add_action('prefix_item_added_to_cart', 'send_email_to_user', $args);

Works

function my_ajax_callback() {

    ...
    // add item to cart
    $cart =. new Cart();
    $cart_id = $cart->add_item($params);

    // if item added successfully
    if($cart_id){
        // send email notification
        wp_mail('set params for email');
    }
    ...

}
Code Lover
  • 8,099
  • 20
  • 84
  • 154
  • It may just be a problem of execution order. When WP execute AJAX call it goes through admin-ajax.php. You should make 100% sure that your "add_action" actually gets called BEFORE the AJAX handler – Diego Oct 19 '20 at 09:36

1 Answers1

0

You just need to call the function. Wherever you're getting your $args from, just pass as param of your function.

// ajax callback function
function my_ajax_callback() {

    ...
    // add item to cart
    $cart =. new Cart();
    $cart_id = $cart->add_item($params);

    // if item added successfully
    if($cart_id){
        // perform action
        send_email_to_user($args);
    }
    ...
    exit(); /// if it's ajax function, don't forget to exit or die.
}
Howard E
  • 5,454
  • 3
  • 15
  • 24