7

I am developing a shop based on Wordpress WooCommerce. I use ajax to make calls for data. But i'm doing it with my own functions in function.php file via wp-admin/admin-ajax.php.

Yesterday I have found in woocommerce class WC_AJAX. My Question is how to enable events from that class, and how to call them from js.

user1559599
  • 495
  • 1
  • 5
  • 17

1 Answers1

4

PHP - Do not wrap in if(is_admin()) like regular WP ajax actions. WC ajax is on the front end:

add_action('wc_ajax_myaction','myaction');
function myaction(){
    exit("Hello. some_var=".$_POST['some_var']);
}

JS - The URL to load is /?wc-ajax=myaction which can be called with a standard XMLHttpRequest or jQuery:

var data={
    some_var:'some value'
}
jQuery.post('/?wc-ajax=myaction',data)
.done(function(result){
    console.log('ajax request completed. result=',result);
})
.fail(function(){
    console.log('ajax request failed. check network log.');
});
dw1
  • 1,495
  • 13
  • 15