WooCommerce - change QTY triggers AJAX call in cart - php

I would like to update and then reload my cart via AJAX when the quantity of an item in the cart is changed.
I can already successfully load in my cart via AJAX.
To load in my cart my php function looks like this. (in my functions.php)
function enqueue_cart_show_ajax() {
wp_register_script( 'cart-show-ajax-js', get_template_directory_uri() . '/js/cart-show-ajax.js', array( 'jquery' ), '', true );
wp_localize_script( 'cart-show-ajax-js', 'cart_show_ajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'cart-show-ajax-js' );
}
add_action('wp_enqueue_scripts', 'enqueue_cart_show_ajax');
function ajax_show_cart() {
echo do_shortcode( '[woocommerce_cart]' );
die();
}
add_action('wp_ajax_show_cart', 'ajax_show_cart');
add_action('wp_ajax_nopriv_show_cart', 'ajax_show_cart');
My Jquery code looks like this (in cart-show-ajax.js)
jQuery(function($) {
//If view-cart is clicked, fill the view-cart-popup window with the cart
$( '.view-cart' ).on('click', function(){
show_cart();
});
//Main ajax function
function show_cart() {
$.ajax({
type: 'GET',
url: cart_show_ajax.ajax_url,
data: {
action: 'show_cart',
},
beforeSend: function ()
{
//You could show a loader here
},
success: function(data)
{
//Hide loader here
$( '.view-cart-popup' ).html(data);
activateReturnToShop();
},
error: function()
{
//If an ajax error has occured, do something here...
$(".product-container").html('<p>There has been an error</p>');
}
});
}
});
The HTML for the cart is as follows
<td class="product-quantity">
<div class="quantity">
<input type="number" step="1" min="0"
name="cart[1e334311e1ef4cf849abff19e4237358][qty]"
value="4" title="Qty" class="input-text qty text" size="4">
</div>
</td>
My best guess is that I can achieve this if when the input is changed I run a function that updates the cart, then simply runs the existing show_cart() function.
I'm not sure about how to make a function that will detect the change to input, grab the new quantity of the product and update the amount in the cart...
It could looks something like:
$( 'input.qty' ).on("change", function(){
// Grab the new product quantity
// Update the cart
show_cart();
});
Anyone know how to get the new quantity update the cart with it?
Thank you for all your help!

Okay so I figured it out!
I can now update cart item's quantities without refreshing via AJAX (:
my functions.php looks like this
//Enqueue Ajax Scripts
function enqueue_cart_qty_ajax() {
wp_register_script( 'cart-qty-ajax-js', get_template_directory_uri() . '/js/cart-qty-ajax.js', array( 'jquery' ), '', true );
wp_localize_script( 'cart-qty-ajax-js', 'cart_qty_ajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'cart-qty-ajax-js' );
}
add_action('wp_enqueue_scripts', 'enqueue_cart_qty_ajax');
function ajax_qty_cart() {
// Set item key as the hash found in input.qty's name
$cart_item_key = $_POST['hash'];
// Get the array of values owned by the product we're updating
$threeball_product_values = WC()->cart->get_cart_item( $cart_item_key );
// Get the quantity of the item in the cart
$threeball_product_quantity = apply_filters( 'woocommerce_stock_amount_cart_item', apply_filters( 'woocommerce_stock_amount', preg_replace( "/[^0-9\.]/", '', filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT)) ), $cart_item_key );
// Update cart validation
$passed_validation = apply_filters( 'woocommerce_update_cart_validation', true, $cart_item_key, $threeball_product_values, $threeball_product_quantity );
// Update the quantity of the item in the cart
if ( $passed_validation ) {
WC()->cart->set_quantity( $cart_item_key, $threeball_product_quantity, true );
}
// Refresh the page
echo do_shortcode( '[woocommerce_cart]' );
die();
}
add_action('wp_ajax_qty_cart', 'ajax_qty_cart');
add_action('wp_ajax_nopriv_qty_cart', 'ajax_qty_cart');
My cart-qty-ajax.js looks like this.
jQuery( function( $ ) {
$( document ).on( 'change', 'input.qty', function() {
var item_hash = $( this ).attr( 'name' ).replace(/cart\[([\w]+)\]\[qty\]/g, "$1");
var item_quantity = $( this ).val();
var currentVal = parseFloat(item_quantity);
function qty_cart() {
$.ajax({
type: 'POST',
url: cart_qty_ajax.ajax_url,
data: {
action: 'qty_cart',
hash: item_hash,
quantity: currentVal
},
success: function(data) {
$( '.view-cart-popup' ).html(data);
}
});
}
qty_cart();
});
});
Works beautifully, though I'm not sure if this is 'good practice'.
Thanks all!

This is a easy ways to resolve this if your are doing the scripting your selves instead of any plugin. Below code will help you to update the cart on quantity dropdown change in customize pop up window where mini cart is displaying:
javascript:
$(document).on('click', '.qty', function (e)
{
e.preventDefault();
var qty = $(this).val();
var cart_item_key = $(this).attr("id");
$.ajax({
type: 'POST',
dataType: 'json',
url: '<?php echo SITE_URL; ?>/wp-admin/admin-ajax.php',
data: {action : 'update_item_from_cart', 'cart_item_key' : cart_item_key, 'qty' : qty, },
success: function (data) {
alert('Updated successfully.');
if (data) {
alert('You missed something');
}else{
alert('Updated Successfully');
}
}
});
});
*In above script .qty is class of the number dropdown.
*Pass two values only i.e cart_item_key and quantity.
*SITE_URL is domain name
*pass two values i.e. qty and cart item key
in functions.php place the below script
function update_item_from_cart() {
$cart_item_key = $_POST['cart_item_key'];
$quantity = $_POST['qty'];
// Get mini cart
ob_start();
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item)
{
if( $cart_item_key == $_POST['cart_item_key'] )
{
WC()->cart->set_quantity( $cart_item_key, $quantity, $refresh_totals = true );
}
}
WC()->cart->calculate_totals();
WC()->cart->maybe_set_cart_cookies();
return true;
}
add_action('wp_ajax_update_item_from_cart', 'update_item_from_cart');
add_action('wp_ajax_nopriv_update_item_from_cart', 'update_item_from_cart');

Related

How to change Woocommerce Variation Image on selection

I'm trying to change the product thumbnail on my Woocommerce website when a variation is selected. I know this has to be done with JS/jQuery but this is not my main skill, so I hope some of you can help me further.
For changing the SKU I found the mix between PHP and JS as below:
<?php
add_action( 'custom_right_side_product_summary', 'wc_product_variable_sku', 45 );
function wc_product_variable_sku() {
global $product;
// $product->is_type( $type ) checks the product type, string/array $type ( 'simple', 'grouped', 'variable', 'external' ), returns boolean
if ( $product->is_type( 'variable' ) ) {
?>
<script type="text/javascript">
jQuery( function($){
$('form.variations_form').on('show_variation', function( event, data ){
$( 'div.widget' ).attr( 'sp-sku', data.sku );
// For testing
//console.log( 'Variation Id: ' + data.variation_id + ' | Sku: ' + data.sku );
//To Show
//document.querySelector(".sku").textContent="NEW SKU: " + data.sku;
document.querySelector(".sku").textContent=data.sku;
});
$('form.variations_form').on('hide_variation', function(){
$( 'div.widget' ).attr( 'sp-sku', '' );
});
});
</script>
<?php
}
}
Now I want to modify this so when a variation is selected the src of the product thumbnail will be replaced. This should make sure the image will be changed. I got the code like below but this is not working yet:
<?php
// ADD SUPPORT FOR VARIABLE IMAGE DISPLAY
add_action( 'custom_left_side_image', 'wc_product_variable_image', 45 );
function wc_product_variable_image() {
global $product;
// $product->is_type( $type ) checks the product type, string/array $type ( 'simple', 'grouped', 'variable', 'external' ), returns boolean
if ( $product->is_type( 'variable' ) ) {
?>
<script type="text/javascript">
jQuery( function($){
$('form.variations_form').on('show_variation', function( event, data ){
$( 'div.widget' ).attr( 'thumb_src', data.image );
// For testing
console.log( 'Variation Id: ' + data.variation_id + ' | Variation Image URL: ' + data.image );
//To Show
document.querySelector(".zoomImg").src="data.image";
});
$('form.variations_form').on('hide_variation', function(){
$( 'div.widget' ).attr( 'thumb_src', '' );
});
});
</script>
<?php
}
}
Something is going wrong, but don't know what. I think the problem is the way I call for an URL but can't find anywhere what another option is. Hope someone can help me solve this.

Add to cart and redirect to checkout for variable products in WooCommerce

I got help in this answer thread that allow to add an additional add-to-cart button that redirects to checkout. It works fine for simple products.
But how to make it work for variable products as well?
I've been trying myself, but no matter what I do, I break the site. I simply do not understand how to make this work with/ for variable products.
Here's the lightly changed code that works for simple products and which takes the quantity field into consideration:
add_action( 'woocommerce_after_add_to_cart_button', 'add_custom_addtocart_and_checkout' );
function add_custom_addtocart_and_checkout() {
global $product;
$addtocart_url = wc_get_checkout_url().'?add-to-cart='.$product->get_id();
$button_class = 'single_add_to_cart_button button alt custom-checkout-btn';
$button_text = __("Buy & Checkout", "woocommerce");
if( $product->is_type( 'simple' )) :
?>
<script>
jQuery(function($) {
var url = '<?php echo $addtocart_url; ?>',
qty = 'input.qty',
button = 'a.custom-checkout-btn';
// On input/change quantity event
$(qty).on('input change', function() {
$(button).attr('href', url + '&quantity=' + $(this).val() );
});
});
</script>
<?php
echo ''.$button_text.'';
endif;
}
Does anyone know how to get this working for variable products too?
Update 3
The following code will handle simple and variable products adding an additional Add to cart button that redirects to cart (with synchronized quantity).
The code works for simple and variable products as well.
add_action( 'woocommerce_after_add_to_cart_button', 'add_custom_addtocart_and_checkout' );
function add_custom_addtocart_and_checkout() {
global $product;
$addtocart_url = wc_get_checkout_url().'?add-to-cart='.$product->get_id();
$button_class = 'single_add_to_cart_button button alt custom-checkout-btn';
$button_text = __("Buy & Checkout", "woocommerce");
if( $product->is_type( 'simple' )) :
?>
<script>
jQuery(function($) {
var url = '<?php echo $addtocart_url; ?>',
qty = 'input.qty',
button = 'a.custom-checkout-btn';
// On input/change quantity event
$(qty).on('input change', function() {
$(button).attr('href', url + '&quantity=' + $(this).val() );
});
});
</script>
<?php
elseif( $product->is_type( 'variable' ) ) :
$addtocart_url = wc_get_checkout_url().'?add-to-cart=';
?>
<script>
jQuery(function($) {
var url = '<?php echo $addtocart_url; ?>',
vid = 'input[name="variation_id"]',
pid = 'input[name="product_id"]',
qty = 'input.qty',
button = 'a.custom-checkout-btn';
// Once DOM is loaded
setTimeout( function(){
if( $(vid).val() != '' ){
$(button).attr('href', url + $(vid).val() + '&quantity=' + $(qty).val() );
}
}, 300 );
// On input/change quantity event
$(qty).on('input change', function() {
if( $(vid).val() != '' ){
$(button).attr('href', url + $(vid).val() + '&quantity=' + $(this).val() );
}
});
// On select attribute field change event
$('.variations_form').on('change blur', 'table.variations select', function() {
if( $(vid).val() != '' ){
$(button).attr('href', url + $(vid).val() + '&quantity=' + $(qty).val() );
}
});
});
</script>
<?php
endif;
echo ''.$button_text.'';
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.

Dynamic discount using AJAX and Fee API in Woocommerce checkout page

I have put a select box in the checkout page like this.
function rx_wc_reward_points_check() {
$reward_points = '<select class="rx-rewad-points" id="rx-redemption-points">
<option value="1250">$25.00 Off (1250 Points) </option>
<option value="2500">$50.00 Off (2500 Points) </option>
<option value="5000">$100.00 Off (5000 Points) </option>
<option value="7000">$150.00 Off (7000 Points) </option>
</select>';
$reward_points .= '<a class="button alt" name="rx_reward_points_btn" id="rx_reward_points" value="Apply" data-value="Reward Points">Apply Now</a>';
echo $reward_points;
}
add_action( 'woocommerce_checkout_after_customer_details', 'rx_wc_reward_points_check', 10, 0 );
After that i have added this to the function file for
function rx_wc_deduct_reward() {
global $woocommerce;
$reward_value = $_POST['rewardpoints'];
WC()->cart->add_fee( 'Fee', -$reward_value );
echo 'success';
exit;
}
add_action( 'wp_ajax_rx_wc_deduct_reward', 'rx_wc_deduct_reward' );
add_action( 'wp_ajax_nopriv_rx_wc_deduct_reward', 'rx_wc_deduct_reward' );
This is using for the ajax part
jQuery(document).ready( function() {
jQuery('#rx_reward_points').on('click', function() {
var selectedrewad = jQuery( "#rx-redemption-points option:selected" ).val();
jQuery.ajax({
type : "post",
url : ajax_var.ajaxurl,
data : { action: "rx_wc_deduct_reward", rewardpoints : selectedrewad },
success: function(response) {
console.log(response)
if(response == "success") {
console.log('done');
}
else {
console.log("Your vote could not be added")
}
}
});
})
})
But it is not working. I have done some mistake in the "rx_wc_deduct_reward" function. I cant figure out how to do this.
Any help is appreciated.
You need to make it slight different to get it work as you get some errors and missing parts:
// Displaying a select field and a submit button in checkout page
add_action( 'woocommerce_checkout_after_customer_details', 'rx_wc_reward_points_check', 10, 0 );
function rx_wc_reward_points_check() {
echo '<select class="rx-rewad-points" id="rx-redemption-points">
<option value="25">' . __("$25.00 Off (1250 Points)", "woocommerce" ) . '</option>
<option value="50">' . __("$50.00 Off (2500 Points)", "woocommerce" ) . '</option>
<option value="100">' . __("$100.00 Off (5000 Points)", "woocommerce" ) . '</option>
<option value="150">' . __("$150.00 Off (7000 Points)", "woocommerce" ) . '</option>
</select>
<a class="button alt" name="rx_reward_points_btn" id="rx_reward_points" value="Apply" data-value="Reward Points">Apply Now</a>';
}
// jQuery - Ajax script
add_action( 'wp_footer', 'rx_wc_reward_points_script' );
function rx_wc_reward_points_script() {
// Only checkout page
if ( ! is_checkout() ) return;
?>
<script type="text/javascript">
jQuery( function($){
if (typeof wc_checkout_params === 'undefined')
return false;
$('#rx_reward_points').on('click', function() {
$.ajax({
type: "post",
url: wc_checkout_params.ajax_url,
data: {
'action' : 'rx_wc_deduct_reward',
'rewardpoints' : $("#rx-redemption-points").val()
},
success: function(response) {
$('body').trigger('update_checkout');
console.log('response: '+response); // just for testing | TO BE REMOVED
},
error: function(error){
console.log('error: '+error); // just for testing | TO BE REMOVED
}
});
})
})
</script>
<?php
}
// Wordpress Ajax code (set ajax data in Woocommerce session)
add_action( 'wp_ajax_rx_wc_deduct_reward', 'rx_wc_deduct_reward' );
add_action( 'wp_ajax_nopriv_rx_wc_deduct_reward', 'rx_wc_deduct_reward' );
function rx_wc_deduct_reward() {
if( isset($_POST['rewardpoints']) ){
WC()->session->set( 'custom_fee', esc_attr( $_POST['rewardpoints'] ) );
echo true;
}
exit();
}
// Add a custom dynamic discount based on reward points
add_action( 'woocommerce_cart_calculate_fees', 'rx_rewardpoints_discount', 20, 1 );
function rx_rewardpoints_discount( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Only for targeted shipping method
if ( WC()->session->__isset( 'custom_fee' ) )
$discount = (float) WC()->session->get( 'custom_fee' );
if( isset($discount) && $discount > 0 )
$cart->add_fee( __( 'Reward discount', 'woocommerce' ), -$discount );
}
Code goes in function.php file of your active child theme (or active theme). Tested and works

JS alert on ajax add to cart for specific product category count in Woocommerce

In Woocommerce I'm trying to display a JavaScript "Sweet alert" when a specific count of products in the cart from a specific category is reached. Items are added to the cart via AJAX which is why I want to use a JavaScript alert (Sweet alert).
e.g. IF cart contains 5 products from category "Bags" - Display alert.
I have researched and found the following helpful answers and used them to build out my code. However, I am struggling with applying the rule to only count products from a specific category.
Display a sweet alert on AJAX add to cart for a specific Woocommerce cart product count
Counting cart-items of specific product category
At the moment, the code below successfully triggers, but only based on the number of products in the cart. It ignores the product category rule:
Loop Through cart items and set the product category counter:
// Wordpress Ajax: Get different cart items count
add_action( 'wp_ajax_nopriv_checking_items', 'checking_items' );
add_action( 'wp_ajax_checking_items', 'checking_items' );
function checking_items() {
global $woocommerce, $product;
$i=0;
// Set minimum product cart total
$total_bags = 0;
$total_shoes = 0;
if( isset($_POST['added'])){
// Loop through cart for product category
foreach ( $woocommerce->cart->cart_contents as $product ) :
if ( has_term( 'bags', 'product_cat', $product['22'] ) ) {
$total_bags += $product['quantity'];
} else {
$total_shoes += $product['quantity'];
}
endforeach;
}
die(); // To avoid server error 500
}
Using jQuery, if count of category met, display JavaScript alert.
// The Jquery script
add_action( 'wp_footer', 'item_check' );
function item_check() {
?>
<script src="https://unpkg.com/sweetalert2#7.20.1/dist/sweetalert2.all.js"></script>
<script type="text/javascript">
jQuery( function($){
// The Ajax function
$(document.body).on('added_to_cart', function() {
console.log('event');
$.ajax({
type: 'POST',
url: wc_add_to_cart_params.ajax_url,
data: {
'action': 'checking_cart_items',
'added' : 'yes'
},
//ONLY DISPLAY ALERT IF TOTAL ITEMS IS FROM CATEGORY BAGS
success: function ($total_bags) {
if($total_bags == 5 ){
//DISPLAY JAVASCRIPT ALERT
const toast = swal.mixin({
toast: true,
showConfirmButton: false,
timer: 3000
});
toast({
type: 'success',
title: '5 Items Added!'
})
}
}
});
});
});
</script>
<?php
}
There is some errors and mistakes in your code. Try this revisited code instead:
// Wordpress Ajax: Get different cart items count
add_action( 'wp_ajax_nopriv_checking_items', 'checking_cart_items' );
add_action( 'wp_ajax_checking_items', 'checking_cart_items' );
function checking_cart_items() {
if( isset($_POST['id']) && $_POST['id'] > 0 ){
// Initialising variables
$count = 0;
$product_id = $_POST['id'];
$category = 'bags';
$category = 't-shirts';
// Loop through cart for product category
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( has_term( $category, 'product_cat', $cart_item['product_id'] ) ) {
$count += $cart_item['quantity'];
}
}
// Only if the added item belongs to the defined product category
if( has_term( $category, 'product_cat', $_POST['id'] ) )
echo $count; // Returned value to jQuery
}
die(); // To avoid server error 500
}
// The Jquery script
add_action( 'wp_footer', 'items_check' );
function items_check() {
if(is_checkout()) return; // Except on checkout page
?>
<script src="https://unpkg.com/sweetalert2#7.20.1/dist/sweetalert2.all.js"></script>
<script type="text/javascript">
jQuery( function($){
// wc_add_to_cart_params is required to continue
if ( typeof wc_add_to_cart_params === 'undefined' )
return false;
$(document.body).on( 'added_to_cart', function( event, fragments, cart_hash, $button ) {
// The Ajax request
$.ajax({
type: 'POST',
url: wc_add_to_cart_params.ajax_url,
data: {
'action': 'checking_items',
'id' : $button.data( 'product_id' ) // Send the product ID
},
//ONLY DISPLAY ALERT IF TOTAL ITEMS IS FROM CATEGORY BAGS
success: function (response) {
console.log('response: '+response); // Testing: to be removed
if(response == 5 ){
//DISPLAY JAVASCRIPT ALERT
const toast = swal.mixin({
toast: true,
showConfirmButton: false,
timer: 3000
});
toast({
type: 'success',
title: '5 Items Added!'
})
}
}
});
});
});
</script>
<?php
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
If you look on your browser inspector javascript console, you will see that ajax is working in the right way, returning each time the items count for that specific product category:

Woocommerce - Product Page - How to create AJAX on "Add To Cart" button?

I want to make an "Add To Cart" button on a product page that would work with AJAX. How can I do it? When I add to cart on a product page - it refreshes the page, how can I make it work by AJAX?
The "Add to cart" button on "Quick View" on archive works by ajax - and it's great, but how can I do the same on product page?
I want to click on "Take me Home" on the product page which would then
add the product with the selected attributes to my cart by ajax and will open that cart (like when you hover onto the bag image on menu) and shakes the bag image.
Just add the following attributes to the Add to Cart button to enable the Ajax button.
<a href="<?php echo $product->add_to_cart_url() ?>" value="<?php echo esc_attr( $product->get_id() ); ?>" class="ajax_add_to_cart add_to_cart_button" data-product_id="<?php echo get_the_ID(); ?>" data-product_sku="<?php echo esc_attr($sku) ?>" aria-label="Add “<?php the_title_attribute() ?>” to your cart">
Add to Cart
</a>
The ajax_add_to_cart add_to_cart_button classes, and the data-product_id="<?php echo get_the_ID(); ?>" data-product_sku="<?php echo esc_attr($sku) ?>" attributes are required.
No need to apply any action or filter.
We can use ajax from archive page. it's easy -
Remove old button which submiting form:
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
Add ajax-link from archive page to single product page:
add_action( 'woocommerce_single_product_summary', 'woocommerce_template_loop_add_to_cart', 30 );
P.S. JS Callback. For example you can show popup with links "Back to shop" and "Cart" or "Checkout"
$('body').on('added_to_cart',function(){
// Callback -> product added
//$('.popup').show();
});
Please start by reading this page:
http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
First you need to add some code to your functions.php for example:
add_action( 'wp_ajax_add_foobar', 'prefix_ajax_add_foobar' );
add_action( 'wp_ajax_nopriv_add_foobar', 'prefix_ajax_add_foobar' );
function prefix_ajax_add_foobar() {
$product_id = intval( $_POST['product_id'] );
// add code the add the product to your cart
die();
}
Then you have to add some javascript code that triggers the add to cart and makes a call to the function:
jQuery( ".add-to-cart" ).each(function()
{
var product_id = jQuery(this).attr('rel');
var el = jQuery(this);
el.click(function() {
var data = {
action: 'add_foobar',
product_id: product_id
};
jQuery.post('/wp-admin/admin-ajax.php' , data, function(response) {
if(response != 0) {
// do something
} else {
// do something else
}
});
return false;
});
});
This is just an example of how it can be done. Although its very basic. This javascript checks for links with the classname .add-to-cart and checks the rel attribute for the corresponding product. It then sends the product id to the php class. There you need to add code to add the corresponding product to the cart.
I suggest you search some more about the topic to make it suit your needs. Good luck.
Woocommerce has come along way. I think the solution is quite easy now. In case I am missing something, all that is required it checking the "Enable AJAX add to cart buttons on archives" and using the woocommerce_template_loop_add_to_cart() function.
The checkbox option is under Woocommerce > Settings > Products > General.
Then simply use woocommerce_template_loop_add_to_cart() wherever you wish to output the button.
If you are using a custom loop like I was, you need to be sure to make the product global in order for the woocommerce_template_loop_add_to_cart() to work.
Below is a small example of using the function:
add_shortcode( 'buy_again' , 'msp_buy_again_shortcode' );
function msp_buy_again_shortcode(){
$order_items = msp_get_customer_unique_order_items( get_current_user_id() );
echo '<div class="owl-carousel owl-theme">';
foreach( $order_items as $id ){
$product = wc_get_product( $id );
global $product;
if( ! empty( $product ) ){
?>
<div class="card buy-again-product">
<a class="link-normal" href="<?php echo $product->get_permalink(); ?>">
<?php echo $product->get_image( 'woocommerce_thumbnail', array( 'class' => 'card-img-top' ) ) ?>
<div class="card-body">
<?php echo wc_get_rating_html( $product->get_average_rating(), $product->get_review_count() ) ?>
<h5><?php echo $product->get_name(); ?></h5>
<p><?php echo $product->get_price_html() ?></p>
<?php woocommerce_template_loop_add_to_cart(); ?>
</div>
</a>
</div>
<?php
}
}
// loop and display buy again.
// try to use the official woocommerce loop.
echo '</div>';
}
Copy this code into your file. For example: my-theme-wc-single-ajax-add-cart.js.
function myThemeWc_SingleProductAddToCart(thisObj) {
if (typeof($) === 'undefined') {
var $ = jQuery.noConflict();
}
var thisForm = thisObj.closest('form');
var button = thisForm.find('.button');
var formUrl = thisForm.attr('action');
var formMethod = thisForm.attr('method');
if (typeof(formMethod) === 'undefined' || formMethod == '') {
formMethod = 'POST';
}
var formData = new FormData(thisForm[0]);
formData.append(button.attr('name'), button.val());
button.removeClass('added');
button.addClass('loading');
myThemeWc_SingleProductCartAjaxTask = $.ajax({
url: formUrl,
method: formMethod,
data: formData,
cache: false,
contentType: false,
processData: false
})
.done(function(data, textStatus, jqXHR) {
$(document.body).trigger('wc_fragment_refresh');
$.when(myThemeWc_SingleProductCartAjaxTask)
.then(myThemeWc_SingleProductUpdateCartWidget)
.done(function() {
button.removeClass('loading');
button.addClass('added');
setTimeout(function() {
button.removeClass('added');
}, 2000);
});
})
.fail(function(jqXHR, textStatus, errorThrown) {
button.removeClass('loading');
})
.always(function(jqXHR, textStatus, errorThrown) {
$('.cart').off('submit');
myThemeWc_SingleProductListenAddToCart();
});
}// myThemeWc_SingleProductAddToCart
function myThemeWc_SingleProductListenAddToCart() {
if (typeof($) === 'undefined') {
var $ = jQuery.noConflict();
}
$('.cart').on('submit', function(e) {
e.preventDefault();
myThemeWc_SingleProductAddToCart($(this));
});
}// myThemeWc_SingleProductListenAddToCart
/**
* Update WooCommerce cart widget by called the trigger and listen to the event.
*
* #returns {undefined}
*/
function myThemeWc_SingleProductUpdateCartWidget() {
if (typeof($) === 'undefined') {
var $ = jQuery.noConflict();
}
var deferred = $.Deferred();
$(document.body).on('wc_fragments_refreshed', function() {
deferred.resolve();
});
return deferred.promise();
}// myThemeWc_SingleProductUpdateCartWidget
var myThemeWc_SingleProductCartAjaxTask;
// on page load --------------------------------------------
jQuery(function($) {
$(document.body).on('wc_fragments_refreshed', function() {
console.log('woocommerce event fired: wc_fragments_refreshed');
});
myThemeWc_SingleProductListenAddToCart();
});
You may need to replace function, variable prefix myThemeWc_ to what you want.
This code use the original WooCommerce single product page add to cart button but stop its functional and then use ajax instead by remain all the values in the form.
Then enqueue this js file.
add_action('wp_enqueue_scripts', 'mythemewc_enqueue_scripts');
function mythemewc_enqueue_scripts() {
if (class_exists('\\WooCommerce') && is_product()) {
wp_enqueue_script('mythemewc-single-product', trailingslashit(get_stylesheet_directory_uri()) . 'assets/js/my-theme-wc-single-ajax-add-cart.js', ['jquery'], false, true);
}
}
You may have to code your css button to make it show the loading, added icon.
Here is css.
.woocommerce #respond input#submit.added::after,
.woocommerce a.btn.added::after,
.woocommerce button.btn.added::after,
.woocommerce input.btn.added::after,
.woocommerce .single_add_to_cart_button.added::after {
font-family: WooCommerce;
content: '\e017';
margin-left: .53em;
vertical-align: bottom;
}
.woocommerce #respond input#submit.loading,
.woocommerce a.btn.loading,
.woocommerce button.btn.loading,
.woocommerce input.btn.loading,
.woocommerce .single_add_to_cart_button.loading {
opacity: .25;
padding-right: 2.618em;
position: relative;
}
.woocommerce #respond input#submit.loading::after,
.woocommerce a.btn.loading::after,
.woocommerce button.btn.loading::after,
.woocommerce input.btn.loading::after,
.woocommerce .single_add_to_cart_button.loading::after {
font-family: WooCommerce;
content: '\e01c';
vertical-align: top;
font-weight: 400;
position: absolute;
right: 1em;
-webkit-animation: spin 2s linear infinite;
animation: spin 2s linear infinite;
}
You can replicate the behavour of the archives button in your single products
add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart'); function woocommerce_ajax_add_to_cart() {
$product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
$quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
$variation_id = absint($_POST['variation_id']);
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
$product_status = get_post_status($product_id);
if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id) && 'publish' === $product_status) {
do_action('woocommerce_ajax_added_to_cart', $product_id);
if ('yes' === get_option('woocommerce_cart_redirect_after_add')) {
wc_add_to_cart_message(array($product_id => $quantity), true);
}
WC_AJAX :: get_refreshed_fragments();
} else {
$data = array(
'error' => true,
'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id));
echo wp_send_json($data);
}
wp_die();
}
add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
function woocommerce_ajax_add_to_cart() {
$product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
$quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
$variation_id = absint($_POST['variation_id']);
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
$product_status = get_post_status($product_id);
if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id) && 'publish' === $product_status) {
do_action('woocommerce_ajax_added_to_cart', $product_id);
if ('yes' === get_option('woocommerce_cart_redirect_after_add')) {
wc_add_to_cart_message(array($product_id => $quantity), true);
}
WC_AJAX :: get_refreshed_fragments();
} else {
$data = array(
'error' => true,
'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id));
echo wp_send_json($data);
}
wp_die();
}
you can see the full tutorial here
https://quadmenu.com/add-to-cart-with-woocommerce-and-ajax-step-by-step/
I used this plugin for the backend part https://wordpress.org/plugins/woo-ajax-add-to-cart/
I'm not using the product page, so I modified the script to work with any button:
(function($) {
$(document).on('click', '.btn', function(e) {
var $thisbutton = $(this);
try {
var href = $thisbutton.prop('href').split('?')[1];
if (href.indexOf('add-to-cart') === -1) return;
} catch (err) {
return;
}
e.preventDefault();
var product_id = href.split('=')[1];
var data = {
product_id: product_id
};
$(document.body).trigger('adding_to_cart', [$thisbutton, data]);
$.ajax({
type: 'post',
url: wc_add_to_cart_params.wc_ajax_url.replace(
'%%endpoint%%',
'add_to_cart'
),
data: data,
beforeSend: function(response) {
$thisbutton.removeClass('added').addClass('loading');
},
complete: function(response) {
$thisbutton.addClass('added').removeClass('loading');
},
success: function(response) {
if (response.error & response.product_url) {
window.location = response.product_url;
return;
} else {
$(document.body).trigger('added_to_cart', [
response.fragments,
response.cart_hash
]);
$('a[data-notification-link="cart-overview"]').click();
}
}
});
return false;
});
})(jQuery);
info: Tested with WooCommerce 2.4.10.
Hmm, well I did it in another way, used the woocommerce loop from add to cart (woocommerce/templates/loop/add-to-cart.php)
global $product;
echo apply_filters( 'woocommerce_loop_add_to_cart_link',
sprintf( '%s',
esc_url( $product->add_to_cart_url() ),
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
esc_attr( isset( $quantity ) ? $quantity : 1 ),
$product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
esc_attr( $product->product_type ),
esc_html( $product->add_to_cart_text() )
),
$product );
BUT the problem was that it was adding just 1 quantity, in fact, you can see in the code that is listed quantity : 1, so I had problems, until I bumped into this guys who saved me
ps. leaving the 1st part where it adds just 1 product for people who don't need more than 1 product in the basket, but I added a solution for those who need more than just 1 product added to the cart.
add-to-cart.js
jQuery( document ).on( 'click', '.product_type_simple', function() {
var post_id = jQuery(this).data('product_id');//store product id in post id variable
var qty = jQuery(this).data('quantity');//store quantity in qty variable
jQuery.ajax({
url : addtocart.ajax_url, //ajax object of localization
type : 'post', //post method to access data
data :
{
action : 'prefix_ajax_add_foobar', //action on prefix_ajax_add_foobar function
post_id : post_id,
quantity: qty
},
success : function(response){
jQuery('.site-header .quantity').html(response.qty);//get quantity
jQuery('.site-header .total').html(response.total);//get total
//loaderContainer.remove();
alert("Product Added successfully..");
}
});
return false;
});
To make ajax woocomerce work on another page you will need.
goes in functions.php
paste this:
remove_action ('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);
add_action ('woocommerce_single_product_summary', 'woocommerce_template_loop_add_to_cart', 30);
in footer.php in the end paste this:
<script>
$ ('body'). on ('add_to_cart', function () {
     // Callback -> product added
     // $ ('. popup'). show ();
});
</script>
For me working exelent. I think this is the simplest solution with Ajax.
+ Add to cart
I used Eh Jewel's answer but then added some custom JS for once the product was added to the cart. This completes the final AJAX process of being able to update the page however you want.
For completeness, here is the HTML code I used (same as Eh Jewel's):
Add to Cart
Then for the custom JS bit:
$(window).on('load', function() {
$('body').on( 'added_to_cart', function( added_to_cart, cart, cart_hash, button ){
// Put the functionality here. Debugging shows you what you have to work with:
console.log('added_to_cart object');
console.log(added_to_cart);
console.log('cart object');
console.log(cart);
console.log('cart_hash object');
console.log(cart_hash);
console.log('button object');
console.log(button);
});
});

Categories