Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Woocommerce WC_AJAX class

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.

like image 935
user1559599 Avatar asked Nov 09 '22 19:11

user1559599


1 Answers

PHP - Do not wrap in if(is_admin()) like regular WP ajax actions. WC ajax is for front-end calls without the overhead of admin:

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

JS - The URL to load is https://example.com/?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.');
});
like image 84
dw1 Avatar answered Nov 14 '22 22:11

dw1