使用WooCommerce Ajax更新购物车 [英] Update cart with WooCommerce ajax
问题描述
在我的woocommerce网站上,我已经更改了购物车页面,删除了更新购物车"按钮,并创建了2个按钮来添加和删除产品,如下图所示:
In my woocommerce website, I have changed the cart page, removed the button "update cart" and create 2 buttons to add and remove items of product like I show in this picture:
当我单击数量按钮时,如果我想按此按钮来更新购物车,我想调用相同的功能.
When I click on the quantity buttons I want to call the same function if I press the button to update the cart.
为此,我正在使用ajax,但是它什么也没做.
For this I am using ajax but it doesn't do anything.
首先在我的function.php
文件中,它是这样的:
First in my function.php
file I have this:
function update_my_cart() {
// here update then cart
var_dump("execute");
}
add_action( 'wp_ajax_update_my_cart', 'update_my_cart' ); // If called from admin panel
add_action( 'wp_ajax_nopriv_update_my_cart', 'update_my_cart' );
add_action( 'wp_enqueue_scripts', 'rct_enqueue_scripts' );
if ( ! function_exists( 'rct_enqueue_scripts' ) ) :
function rct_enqueue_scripts() {
wp_enqueue_script( 'rct-js', get_template_directory_uri() . '/js/themeCoffee.js', array(), '1.0', true );
wp_localize_script('rct-js', 'ajax_object', array('ajax_url' => admin_url( 'admin-ajax.php' )));
}
endif;
在我的jquery文件中,我有这个:
And in my jquery file I have this:
updatecart = function(qty) {
var currentVal, data, item_hash, request;
currentVal = void 0;
data = void 0;
item_hash = void 0;
currentVal = parseFloat(qty);
request = $.ajax({
url: 'ajax_object.ajax_url',
method: 'POST',
data: {
quantity: currentVal,
action: 'update_my_cart'
},
dataType: 'html'
});
request.done(function(msg) {
alert('cart update ');
});
request.fail(function(jqXHR, textStatus) {
alert('Request failed: ' + textStatus);
});
};
我收到此错误:
Failed to load resource: the server responded with a status of 404 (Not Found)
因为我尝试加载my_website/cart/ajax_object.ajax_url
.
提前谢谢!
推荐答案
您已经忘记了以下基本过程:
You have forget this essential process:
add_action('wp_enqueue_scripts', 'add_my_ajax_scripts');
function add_my_ajax_scripts() {
// Here you register your script located in a subfolder `js` of your active theme
wp_enqueue_script( 'ajax-script', get_template_directory_uri().'/js/script.js', array('jquery'), '1.0', true );
// Here you are going to make the bridge between php and js
wp_localize_script( 'ajax-script', 'cart_ajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
然后,您将在JavaScript文件中的"url:
"中检索"ajaxurl
"和"cart_ajax
":
Then you will retrieve "ajaxurl
" and "cart_ajax
" in your javascript file in "url:
":
$.ajax({
url: cart_ajax.ajaxurl,
...
})
您的javascript函数将无法正常工作. 以下是一些功能示例:您需要执行的操作:
Your javascript function will not work. Here are some functional examples of what you need to do:
WordPress传递使用Wordpress将ajax值转换为特定页面
如何可以将Ajax与您的WordPress插件或主题一起使用?
这篇关于使用WooCommerce Ajax更新购物车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!