13

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?

estrar
  • 1,373
  • 4
  • 12
  • 37
  • You have to generate a new html for that product and append it to html. Also change number of how many items are in cart and some other things, maybe. Try searching for the HTML that generate the cart and translate it into javascript. Do it or via string concat, or via javascript templates (which are so cool). – ioan May 10 '13 at 13:47

5 Answers5

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

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

}
user319940
  • 3,267
  • 8
  • 38
  • 53
  • 1
    Could you be a little more precise about the modification? For instance, can I get the item data with 'add_to_cart_fragments'? – Luc Oct 22 '14 at 16:39
1

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'*/
            }); 
      }
klewis
  • 7,459
  • 15
  • 58
  • 102
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 :

<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

npradeetw
  • 358
  • 1
  • 3
  • 7
  • Thank you. It should already be a function within woocommerce that handles this? When I press "add to cart"-buttons generated by woocommerce the product gets added without a page reload. I'm kind of looking for this function so I can use it myself for my own woocommerce customization, instead of reinventing something that should already exist. – estrar May 17 '13 at 08:49
0

This seems to work well for me, at least on the themes that I tried:

jQuery( document.body ).trigger( 'wc_fragment_refresh' );
Nikolay
  • 359
  • 3
  • 7
0
jQuery( "body" ).on( "submit", "#club_login_form", function(e) {
    e.preventDefault();
    var product_id = $(this).closest('form').find('.club-member_id').attr('data-id');
    if(product_id!=''){
        jQuery.ajax({
            type: "POST",
            url: _object.ajaxurl,
            data: {
                action:'club_member_add_product',
                'product_id':product_id,
                'quantity': 1
            },
            success: function(data) {
               // console.log(data);
                jQuery('.club-register-modal').modal('hide');
                jQuery( document.body ).trigger( 'wc_fragment_refresh' );
                jQuery('body').addClass('mini_cart_active');
            }
        });
    }

});
add_action('wp_ajax_callback_function', 'callback_function');
add_action('wp_ajax_nopriv_callback_function', 'callback_function');
function callback_function(){

    $product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
    $quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
    $product_status = get_post_status($product_id);


    $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);

    if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity) && 'publish' === $product_status) {
        do_action('woocommerce_ajax_added_to_cart', $product_id);
        echo json_encode(array('success' => true, 'message' => 'Product added to cart.'));
    }

    wp_die();
}
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 09 '23 at 10:39