Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update cart with WooCommerce ajax

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:

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.

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;

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

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.

Thanks in advance!

like image 471
Stone Avatar asked Jun 08 '16 18:06

Stone


People also ask

How do I automatically update WooCommerce cart?

Setting the cart page to auto update means that when a product's quantity is changed the cart totals will automatically be updated without the user needing to click a button. To enable this feature navigate to Appearance > Customize > WooCommerce > Cart and enable the Auto Update setting.

How do I add Ajax to cart in WooCommerce?

One way to add AJAX to your WooCommerce cart is to use the WooCommerce Ajax Add to Cart plugin. This plugin is available for free from the WordPress plugin repository. Once installed and activated, you can configure the plugin settings from the WooCommerce > Settings > Ajax Add to Cart tab.

Does WooCommerce use Ajax?

The Ajax-Enabled, Layered Navigation extension for WooCommerce provides a richer user experience for your customer and is particularly well suited for stores that have a lot of variable products or products with a number of attributes.

What is enable Ajax add to cart?

The plugin we're using here is a product of QuadLayers, called AJAX add to cart WooCommerce. This plugin is easy to use, free, and can be found in the WordPress plugin directory. This tool enables customers to add single or variable items to their shopping carts without having to reload the site each time.


2 Answers

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:":

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

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

  • WooCommerce - auto update total price when quantity changed?

  • Wordpress passing ajax value to a specific page using Wordpress

  • Using AJAX With PHP on Your WordPress Site Without a Plugin

  • How to use Ajax with your WordPress Plugin or Theme?

like image 106
LoicTheAztec Avatar answered Sep 17 '22 14:09

LoicTheAztec


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

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

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

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.

JQuery code is below, I suggest placing it in js file and enqueuing in dependency with jQuery, then it works with 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 );
});
like image 21
Ryszard Jędraszyk Avatar answered Sep 19 '22 14:09

Ryszard Jędraszyk