php 使用 WooCommerce ajax 更新购物车

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37710770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:20:37  来源:igfitidea点击:

Update cart with WooCommerce ajax

phpjqueryajaxwordpresswoocommerce

提问by Stone

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:

在我的 woocommerce 网站中,我更改了购物车页面,删除了“更新购物车”按钮并创建了 2 个按钮来添加和删除产品项目,如下图所示:

enter image description here

在此处输入图片说明

When I click on the quantity buttons I want to call the same function if I press the button to update the cart.

当我点击数量按钮时,如果我按下按钮来更新购物车,我想调用相同的功能。

For this I am using ajax but it doesn't do anything.

为此,我正在使用 ajax,但它没有做任何事情。

First in my function.phpfile I have this:

首先在我的function.php文件中我有这个:

  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;

And in my jquery file I have this:

在我的 jquery 文件中,我有这个:

  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);
    });
  };   

I obtain this error:

我得到这个错误:

Failed to load resource: the server responded with a status of 404 (Not Found)

Because I try to load my_website/cart/ajax_object.ajax_url.

因为我尝试加载my_website/cart/ajax_object.ajax_url.

Thanks in advance!

提前致谢!

回答by LoicTheAztec

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' ) ) );
}

Then you will retrieve "ajaxurl" and "cart_ajax" in your javascript file in "url:":

然后,您将在ajaxurlcart_ajax”中的 javascript 文件中检索“ ”和“ url:”:

$.ajax({
  url: cart_ajax.ajaxurl,
  ...
})

Your javascript function will not work. Here are some functional examplesof what you need to do:

您的 javascript 函数将不起作用。以下是您需要执行的一些功能示例

回答by Ryszard J?draszyk

Since WooCommerce 2.6.0, released June 2016, WooCommerce cart page uses Ajax to update cart totals after clicking on Update cart button.

自 2016 年 6 月发布的 WooCommerce 2.6.0 以来,WooCommerce 购物车页面在单击“更新购物车”按钮后使用 Ajax 更新购物车总数。

It's no longer needed to create your own Ajax call, the one assigned to Update cart button can be used.

不再需要创建自己的 Ajax 调用,可以使用分配给“更新购物车”按钮的调用。

I created a free plugin Ajax Cart AutoUpdate for WooCommercewhich updates cart page and mini cart after changing product quantity and provides some customization options for this process.

为 WooCommerce创建了一个免费插件Ajax Cart AutoUpdate,它在更改产品数量后更新购物车页面和迷你购物车,并为此过程提供了一些自定义选项。

The most important thing is to set update delay. If user changes quantity again during this delay, it will be reset to full duration. If it's not implemented and you change quantity from 1 to 10 by clicking on increment button, it will trigger 9 Ajax calls instead of 1.

最重要的是设置更新延迟。如果用户在此延迟期间再次更改数量,它将重置为完整持续时间。如果它没有实现并且您通过单击增量按钮将数量从 1 更改为 10,它将触发 9 个 Ajax 调用而不是 1 个。

JQuery code is below, I suggest placing it in js file and enqueuing in dependency with jQuery, then it works with jQuery deferred:

JQuery 代码如下,我建议将它放在 js 文件中并使用 jQuery 依赖入队,然后它可以与 jQuery deferred 一起使用:

var timeout;

jQuery('div.woocommerce').on('change keyup mouseup', 'input.qty', function(){ // keyup and mouseup for Firefox support
    if (timeout != undefined) clearTimeout(timeout); //cancel previously scheduled event
    if (jQuery(this).val() == '') return; //qty empty, instead of removing item from cart, do nothing
    timeout = setTimeout(function() {
        jQuery('[name="update_cart"]').trigger('click');
    }, 1000 );
});