添加产品后更新Woocommerce购物车(jQuery)

时间:2021-08-04 19:20:55

The Ajax seems to work just fine but the cart content won't refresh as expected. I want the contents of the cart to be refreshed once the "add to cart" button is clicked. As it is now, I have to refresh the page manually to see the added products.

Ajax似乎工作正常,但购物车内容不会按预期刷新。单击“添加到购物车”按钮后,我希望刷新购物车的内容。就像现在一样,我必须手动刷新页面以查看添加的产品。

I'm using this function to add a product to my woocommerce cart:

我正在使用此功能将产品添加到我的woocommerce购物车:

      function addToCart(p_id) {
            jQuery.ajax({
              type: 'POST',
              url: '/wp/?post_type=product&add-to-cart='+p_id,
              data: { 'product_id':  p_id,
              'quantity': amount},
              success: function(response, textStatus, jqXHR){
                    console.log("Product added");
                }/*,
              dataType: 'JSON'*/
            }); 
      }

    jQuery('#addToCart').click(function(e) {
      e.preventDefault();
      addToCart(prod_id["product_id"]);
      return false;
    });  

Is it possible to refresh only the cart after a product was added?

添加产品后是否可以仅刷新购物车?

3 个解决方案

#1


7  

This is possible - you need to use a modified version of this code:

这是可能的 - 您需要使用此代码的修改版本:

http://docs.woothemes.com/document/show-cart-contents-total/

Edit - in case of future 404's

编辑 - 在未来404的情况下

<a class="cart-customlocation" href="<?php echo wc_get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php echo sprintf ( _n( '%d item', '%d items', WC()->cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?> - <?php echo WC()->cart->get_cart_total(); ?></a>

// Ensure cart contents update when products are added to the cart via AJAX (place the following in functions.php).
// Used in conjunction with https://gist.github.com/DanielSantoro/1d0dc206e242239624eb71b2636ab148
add_filter('add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment');

function woocommerce_header_add_to_cart_fragment( $fragments ) {
    global $woocommerce;

    ob_start();

    ?>
    <a class="cart-customlocation" href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>"><?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count);?> - <?php echo $woocommerce->cart->get_cart_total(); ?></a>
    <?php

    $fragments['a.cart-customlocation'] = ob_get_clean();

    return $fragments;

}

#2


1  

Do you mind if the ajax request "automatically" refreshes the page on its own? then you could try something like this... (untested).

你是否介意ajax请求是否“自动”刷新页面?然后你可以尝试这样的事情......(未经测试)。

 function addToCart(p_id) {
            jQuery.ajax({
              type: 'POST',
              url: '/wp/?post_type=product&add-to-cart='+p_id,
              data: { 'product_id':  p_id,
              'quantity': amount},
              success: function(response, textStatus, jqXHR){
                    location.reload(true);
                }/*,
              dataType: 'JSON'*/
            }); 
      }

#3


0  

First observe what is the html in the cart and what all information you require to fulfill that. Example your cart may look something like this :

首先观察购物车中的html以及实现该功能所需的所有信息。您的购物车示例可能如下所示:

<div id="cart">
  <form action="checkout" method="POST" id="cart_checkout_form">
    <table id="cart_table">
      <tr>
         <td> Product </td>
         <td> Qty </td>
         <td> Price </td>
      </tr> 
      <tr>
         <td> <input type="hidden" name="product_id" value="221321"/> Product 1</td>
         <td> 2</td>
         <td> 200 $</td>
      </tr>

    </table>

  </form>
</div>

Now your code should contain the following changes to reflect the product:

现在,您的代码应包含以下更改以反映产品:

 function addToCart(p_id) {
        jQuery.ajax({
          type: 'POST',
          url: '/wp/?post_type=product&add-to-cart='+p_id,
          data: { 'product_id':  p_id,
          'quantity': amount},
          success: function(response, textStatus, jqXHR){
                /* response should contain details required for adding to cart

                   like price quantity name etc in the json response */

                var new_product_html = "<tr><td><input type='hidden' value='"+ response.product_id +"' name="product_id"/>"+ response.product_name +" </td><td>"+response.product_qty+"</td><td>"+ response.product_price +"</td></tr>";

                $("#cart_table").append(new_product_html);

                console.log("Product added");

            }/*,
          dataType: 'JSON'*/
        }); 
  }

jQuery('#addToCart').click(function(e) {
  e.preventDefault();
  addToCart(prod_id["product_id"]);
  return false;
}); 

This will reflect in getting the product added to the cart. Please read the following links if you find it confusing. Tutorial Also jquery append and ajax functions in more detail at jquery.com

这将反映在将产品添加到购物车中。如果您感到困惑,请阅读以下链接。教程还可以在jquery.com上更详细地了解jquery append和ajax函数

#1


7  

This is possible - you need to use a modified version of this code:

这是可能的 - 您需要使用此代码的修改版本:

http://docs.woothemes.com/document/show-cart-contents-total/

Edit - in case of future 404's

编辑 - 在未来404的情况下

<a class="cart-customlocation" href="<?php echo wc_get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php echo sprintf ( _n( '%d item', '%d items', WC()->cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?> - <?php echo WC()->cart->get_cart_total(); ?></a>

// Ensure cart contents update when products are added to the cart via AJAX (place the following in functions.php).
// Used in conjunction with https://gist.github.com/DanielSantoro/1d0dc206e242239624eb71b2636ab148
add_filter('add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment');

function woocommerce_header_add_to_cart_fragment( $fragments ) {
    global $woocommerce;

    ob_start();

    ?>
    <a class="cart-customlocation" href="<?php echo $woocommerce->cart->get_cart_url(); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>"><?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count);?> - <?php echo $woocommerce->cart->get_cart_total(); ?></a>
    <?php

    $fragments['a.cart-customlocation'] = ob_get_clean();

    return $fragments;

}

#2


1  

Do you mind if the ajax request "automatically" refreshes the page on its own? then you could try something like this... (untested).

你是否介意ajax请求是否“自动”刷新页面?然后你可以尝试这样的事情......(未经测试)。

 function addToCart(p_id) {
            jQuery.ajax({
              type: 'POST',
              url: '/wp/?post_type=product&add-to-cart='+p_id,
              data: { 'product_id':  p_id,
              'quantity': amount},
              success: function(response, textStatus, jqXHR){
                    location.reload(true);
                }/*,
              dataType: 'JSON'*/
            }); 
      }

#3


0  

First observe what is the html in the cart and what all information you require to fulfill that. Example your cart may look something like this :

首先观察购物车中的html以及实现该功能所需的所有信息。您的购物车示例可能如下所示:

<div id="cart">
  <form action="checkout" method="POST" id="cart_checkout_form">
    <table id="cart_table">
      <tr>
         <td> Product </td>
         <td> Qty </td>
         <td> Price </td>
      </tr> 
      <tr>
         <td> <input type="hidden" name="product_id" value="221321"/> Product 1</td>
         <td> 2</td>
         <td> 200 $</td>
      </tr>

    </table>

  </form>
</div>

Now your code should contain the following changes to reflect the product:

现在,您的代码应包含以下更改以反映产品:

 function addToCart(p_id) {
        jQuery.ajax({
          type: 'POST',
          url: '/wp/?post_type=product&add-to-cart='+p_id,
          data: { 'product_id':  p_id,
          'quantity': amount},
          success: function(response, textStatus, jqXHR){
                /* response should contain details required for adding to cart

                   like price quantity name etc in the json response */

                var new_product_html = "<tr><td><input type='hidden' value='"+ response.product_id +"' name="product_id"/>"+ response.product_name +" </td><td>"+response.product_qty+"</td><td>"+ response.product_price +"</td></tr>";

                $("#cart_table").append(new_product_html);

                console.log("Product added");

            }/*,
          dataType: 'JSON'*/
        }); 
  }

jQuery('#addToCart').click(function(e) {
  e.preventDefault();
  addToCart(prod_id["product_id"]);
  return false;
}); 

This will reflect in getting the product added to the cart. Please read the following links if you find it confusing. Tutorial Also jquery append and ajax functions in more detail at jquery.com

这将反映在将产品添加到购物车中。如果您感到困惑,请阅读以下链接。教程还可以在jquery.com上更详细地了解jquery append和ajax函数