简体   繁体   中英

Update Woocommerce cart after adding a product (jQuery)

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.

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

      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?

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

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

}

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

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

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 :

<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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM