Image not replacing with variation image - php

I am trying to create a function which replaces the head image with the variation image clicked. I did make a function but I am getting an error in the console. Here is the function:
// add this to functions.php
add_action('woocommerce_after_single_product','custom_woocommerce_additional_variation_images');
function custom_woocommerce_additional_variation_images(){
?>
<script type="text/javascript">
(function($) {
$(window).load(function(){
$( "a.swatch-anchor").click(function() {
//console.log(variation);
var atts = $(this).parent().attr('data-value');
var product_variations = $('form.variations_form').data('product_variations');
console.log(product_variations);
var variation_id = '';
for ( var i = 0; i < product_variations.length; i++ ) {
var variation = product_variations[i];
if( product_variations[i].attributes.attribute_pa_kleur == atts){
variation_id = product_variations[i].variation_id;
}
}
console.log(variation_id);
var data = {
security: wc_additional_variation_images_local.ajaxImageSwapNonce,
variation_id: variation_id,
post_id: $( 'form.variations_form' ).data( 'product_id' )
};
$.ajax({
type: "POST",
url: $.wc_additional_variation_images_frontend.getAjaxURL( 'get_images' ),
data: data,
cache: false,
success: function(data,response){
data = $.parseJSON(data);
console.log(data['main_images']);
$('.woocommerce-product-gallery').replaceWith(data['main_images']);
},
});
});
})
})(jQuery);
</script>
<?php
}
add_filter( 'wc_additional_variation_images_custom_swap', '__return_true');
add_filter( 'wc_additional_variation_images_custom_reset_swap', '__return_true' );
add_filter( 'wc_additional_variation_images_custom_original_swap', '__return_true' );
add_filter( 'wc_additional_variation_images_get_first_image', '__return_true' );
The console is returning: Uncaught ReferenceError: wc_additional_variation_images_local is not defined
Here is the website which I am using: https://www.dev.ruitershopboxmeer.nl/product/kingsland-zadeldekje-carin/
Does anyone know what I am doing wrong?

Related

WooCommerce shopping mini cart isn't updated after ajax adding items

I made adding multiple items with quantity to the cart using AJAX.
After adding a product, the mini cart isn't updated, but WC_AJAX :: get_refreshed_fragments () is called in function.php and I have a hook to update the cart woocommerce_add_to_cart_fragments.
How to force to update the mini cart or what needs to be fixed in this code.
JS
productsToAdd // array with id and quantity
$(document).on('click', '.buy-tovar', function (e) {
e.preventDefault();
productsToAdd.forEach(function(item){
var data = {
action: 'woocommerce_ajax_add_to_cart',
product_id: item['id'],
quantity: item['quantity']
};
$.ajax({
type: 'post',
url: wc_add_to_cart_params.ajax_url,
data: data,
async: false,
success: function (response) {
$('.buy-tovar').addClass("added");
},
});
});
});
PHP
add_filter( 'woocommerce_add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment' );
function woocommerce_header_add_to_cart_fragment( $fragments ) {
ob_start();
?>
<a href="<?php echo wc_get_cart_url(); ?>" class="cart">
<div class="img-block">
<img src="<?php echo get_template_directory_uri();?>/image/cart.png" alt="">
<span><?php echo count( WC()->cart->get_cart()); ?></span>
</div>
</a>
<?php
$fragments['a.cart'] = ob_get_clean();
return $fragments;
}
//AJAX
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 = absint($_POST['quantity']);
$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) && '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();
}
I found a solution i added the line in my JS:
$(document.body).trigger('wc_fragment_refresh');
Full code JS
document).on('click', '.buy-tovar', function (e) {
e.preventDefault();
productsToAdd.forEach(function(item){
var data = {
action: 'woocommerce_ajax_add_to_cart',
product_id: item['id'],
quantity: item['quantity']
};
$.ajax({
type: 'post',
url: wc_add_to_cart_params.ajax_url,
data: data,
async: false,
success: function (response) {
$('.buy-tovar').addClass("added");
$(document.body).trigger('wc_fragment_refresh');
},
});
});
});

Replace "added to cart" notice with JS Sweet Alert on WooCommerce

I've removed the standard "Added to cart" message given by WooCommerce. I have then added the code below which is using the Sweet Alert. The idea is to remove all "added to cart" messages and to only use the sweet alert.
Based on "JS alert on ajax add to cart for specific product category count in Woocommerce" answer code by #LoicTheAztec, my code works for the first product added, but not for the following ones. So it works fine when the cart is empty and when adding the first product.
Here's the code I'm using:
// remove add to cart woocommerce message
add_filter('wc_add_to_cart_message_html', '__return_null');
// Wordpress Ajax PHP
add_action('wp_ajax_nopriv_checking_items', 'atc_sweet_message');
add_action('wp_ajax_checking_items', 'atc_sweet_message');
function atc_sweet_message() {
if (isset($_POST['id']) && $_POST['id'] > 0) {
$count = 0;
$product_id = $_POST['id'];
foreach(WC()-> cart-> get_cart() as $cart_item) {
$count += $cart_item['quantity'];
}
}
echo $count;
die();
}
// jQuery Ajax
add_action('wp_footer', 'item_count_check');
function item_count_check() {
if (is_checkout())
return;
?>
<script src="https://unpkg.com/sweetalert2#7.20.1/dist/sweetalert2.all.js"></script>
<script type="text/javascript">
jQuery( function($) {
if ( typeof wc_add_to_cart_params === 'undefined' )
return false;
$(document.body).on( 'added_to_cart', function( event, fragments, cart_hash, $button ) {
$.ajax({
type: 'POST',
url: wc_add_to_cart_params.ajax_url,
data: {
'action': 'checking_items',
'id' : $button.data( 'product_id' )
},
success: function (response) {
if(response == 1 ){
const toast = swal.mixin({
toast: true,
showConfirmButton: false,
timer: 3000
});
toast({
type: 'success',
title: 'Product Added To Cart'
})
}
}
});
});
});
</script>
<?php
}
I tried removing if(response == 1 ){ without success. Any input on this is appreciated.
There was little mistakes in your code on the function for Wordpress Ajax PHP. Try the following:
// remove add to cart woocommerce message
add_filter('wc_add_to_cart_message_html', '__return_null');
// Wordpress Ajax PHP
add_action('wp_ajax_nopriv_item_added', 'addedtocart_sweet_message');
add_action('wp_ajax_item_added', 'addedtocart_sweet_message');
function addedtocart_sweet_message() {
echo isset($_POST['id']) && $_POST['id'] > 0 ? (int) esc_attr($_POST['id']) : false;
die();
}
// jQuery Ajax
add_action('wp_footer', 'item_count_check');
function item_count_check() {
if (is_checkout())
return;
?>
<script src="https://unpkg.com/sweetalert2#7.20.1/dist/sweetalert2.all.js"></script>
<script type="text/javascript">
jQuery( function($) {
if ( typeof wc_add_to_cart_params === 'undefined' )
return false;
$(document.body).on( 'added_to_cart', function( event, fragments, cart_hash, $button ) {
var $pid = $button.data('product_id');
$.ajax({
type: 'POST',
url: wc_add_to_cart_params.ajax_url,
data: {
'action': 'item_added',
'id' : $pid
},
success: function (response) {
if(response == $pid){
const toast = swal.mixin({
toast: true,
showConfirmButton: false,
timer: 3000
});
toast({
type: 'success',
title: 'Product Added To Cart'
})
}
}
});
});
});
</script>
<?php
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
It works now for all ajax added to cart items (and not just the first one).

AJAX Wordpress ACF update with button click id

I using ACF wordpress to update acf field for user to populate with button id click.
I am getting Error as admin-ajax.php with 400
Error POST https://domainname/wp-admin/admin-ajax.php 400 ()
Wordpress code on template
<button class="get_project" id="1479" name="urbtnid" data-postid="147">Get project</button>
<button class="get_userbtn" value="<?php echo get_current_user_id() ?>" id="get_userbtn" ><?php echo get_current_user_id() ?></button>
**
JQUery AJAX Code
**
jQuery(function($){
$('.get_project').click(function() {
var stdid = jQuery('#get_userbtn').attr('value');
var stdbtnid = this.id;
jQuery.ajax({
url: my_ajax_object.ajax_url,
type : 'post',
data: dataString,
success : function( response ) {
console.log(response);
}
});
})
});
**
Function.php code
**
function my_enqueue_ajax_save() {
wp_register_script( 'ajax-script', get_template_directory_uri() . '/pradeep-js-css/my-ajax-id-save-script.js', array('jquery') , false, true );
wp_enqueue_script( 'ajax-script' );
wp_localize_script( 'ajax-script', 'my_ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_ajax_save' );
add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
function my_action(){
$postid = $_POST['stdid1'];;
$fieldname = 'last_question_viewed';
$fieldvalue = $_POST['stdbtnid1'];
update_post_meta($postid, $fieldname, $fieldvalue);
echo $postid;
wp_die($fieldname = '', $fieldvalue = '', $postid = '');
}
Updated jquery with action
jQuery(function($){
var stdid = jQuery('#get_userbtn').attr('value');
var stdbtnid = this.id;
var dataString = 'stdid1=' + stdid + '&stdbtnid1=' + stdbtnid;
$('.get_project').click(function() {
var data = {
action: "my_action",
stdid: stdid,
stdbtnid1: stdbtnid
};
jQuery.ajax({
url: my_ajax_object.ajax_url,
type : 'post',
data: data,
success : function( response ) {
console.log(response);
}
});
})
});

Called and canceled of the admin-ajax.php file multiple times

I have an issue in a Wordpress installation with a plugin. There is a calendar which you can click on a day (or a range of days) and from ajax calls through admin-ajax.php it calculates product costs.
The problem is that, when I click on a calendar cell, the admin-ajax.php is called twice. The first time for a few milliseconds and canceled immediately. Then automatically, it calls it once again and get the ajax response. When I click for a second time on a calendar cell, the admin-ajax.php is called 3 times. The first two are canceled and only the last one get a response.
I found that the code that is used for this part is the following. However, I cannot find any issue on it, even if I can see those cancelled calls on Developer console.
$('.wc-bookings-booking-form')
.on('change', 'input, select', function() {
var index = $('.wc-bookings-booking-form').index(this);
if ( xhr[index] ) {
xhr[index].abort();
}
$form = $(this).closest('form');
var required_fields = $form.find('input.required_for_calculation');
var filled = true;
$.each( required_fields, function( index, field ) {
var value = $(field).val();
if ( ! value ) {
filled = false;
}
});
if ( ! filled ) {
$form.find('.wc-bookings-booking-cost').hide();
return;
}
$form.find('.wc-bookings-booking-cost').block({message: null, overlayCSS: {background: '#fff', backgroundSize: '16px 16px', opacity: 0.6}}).show();
xhr[index] = $.ajax({
type: 'POST',
url: booking_form_params.ajax_url,
data: {
action: 'wc_bookings_calculate_costs',
form: $form.serialize()
},
success: function( code ) {
if ( code.charAt(0) !== '{' ) {
console.log( code );
code = '{' + code.split(/\{(.+)?/)[1];
}
result = $.parseJSON( code );
if ( result.result == 'ERROR' ) {
$form.find('.wc-bookings-booking-cost').html( result.html );
$form.find('.wc-bookings-booking-cost').unblock();
$form.find('.single_add_to_cart_button').addClass('disabled');
} else if ( result.result == 'SUCCESS' ) {
$form.find('.wc-bookings-booking-cost').html( result.html );
$form.find('.wc-bookings-booking-cost').unblock();
$form.find('.single_add_to_cart_button').removeClass('disabled');
} else {
$form.find('.wc-bookings-booking-cost').hide();
$form.find('.single_add_to_cart_button').addClass('disabled');
console.log( code );
}
},
error: function() {
$form.find('.wc-bookings-booking-cost').hide();
$form.find('.single_add_to_cart_button').addClass('disabled');
},
dataType: "html"
});
})
.each(function(){
var button = $(this).closest('form').find('.single_add_to_cart_button');
button.addClass('disabled');
});
And here is a screenshot from the Dev Console:
EDIT: I think I found the problem, but I am not sure. There is also this part of code which was supposed to not used at all. There is a feature for time on calendar, but it isn't activated. So, this code should not be run.
$('.wc-bookings-booking-form').on( 'date-selected', function() {
show_available_time_blocks( this );
});
var xhr;
function show_available_time_blocks( element ) {
var $form = $(element).closest('form');
var block_picker = $form.find('.block-picker');
var fieldset = $form.find('.wc_bookings_field_start_date');
var year = parseInt( fieldset.find( 'input.booking_date_year' ).val(), 10 );
var month = parseInt( fieldset.find( 'input.booking_date_month' ).val(), 10 );
var day = parseInt( fieldset.find( 'input.booking_date_day' ).val(), 10 );
if ( ! year || ! month || ! day ) {
return;
}
// clear blocks
block_picker.closest('div').find('input').val( '' ).change();
block_picker.closest('div').block({message: null, overlayCSS: {background: '#fff', backgroundSize: '16px 16px', opacity: 0.6}}).show();
// Get blocks via ajax
if ( xhr ) xhr.abort();
xhr = $.ajax({
type: 'POST',
url: booking_form_params.ajax_url,
data: {
action: 'wc_bookings_get_blocks',
form: $form.serialize()
},
success: function( code ) {
block_picker.html( code );
resize_blocks();
block_picker.closest('div').unblock();
},
dataType: "html"
});
}

Dynamically adding Meta Key Name in Wordpress using jQuery

I have jQuery function that dynamically adds the Meta Key Name and Meta Key Value in Wordpress when a a checkbox in a certain custom post type is clicked. Currently the function Stores the post Id as the Meta Key Name but I would like to change this to say checkbox_meta_key so all posts under this custom post type have this Meta Key Name.
(function($){
$('li.todo').click(function(){
if($(this).find('.uncheck_box').length >0){
var _t=$(this).find('.uncheck_box');
_t.removeClass('uncheck_box');
_t.addClass('check_box');
m_val='1';
$(this).find('a').addClass('strike');
}else{
m_val='0';
var _t=$(this).find('.check_box');
_t.removeClass('check_box');
_t.addClass('uncheck_box');
$(this).find('a').removeClass('strike');
}
//trigger a custom event here
$(this).trigger('updateclass')
var m_key=jQuery(this).attr('id');
jQuery.ajax({
type: "POST",
url: "<?php echo get_template_directory_uri(); ? >/ajax_get.php",
data: { meta_key: m_key, meta_value: m_val},
beforeSend: function( ) {
//jQuery(this).attr("disabled", true);
},
success:function(){}
})
});
var $checkboxes = jQuery('li.todo'),
$completeCount = jQuery('.complete-count'),
$incompleteCount = jQuery('.incomplete-count');
var updateCount = function(){
$completeCount.text(jQuery('.check_box').length);
$incompleteCount.text(jQuery('.uncheck_box').length);
};
$checkboxes.on('updateclass', updateCount);
updateCount();
$('.sort, .itemage').on('click', function (e) {
var $this = $(this).hasClass('sort') ? $(this).addClass('active') : $('.sort.active');
var itemage = $('.itemage').val(),
b = itemage == 10;
$('.sort').not($this).removeClass('active');
if ($this.hasClass('showall')) {
$('li.todo').hide().filter(function () {
return (this.getAttribute('itemage') === itemage || b);
}).show();
return;
}
var sel = $this.hasClass('incomplete') ? 'span.uncheck_box' : 'span.check_box';
$('li.todo').hide().filter(function () {
return (this.getAttribute('itemage') === itemage || b) && !! $(this).find(sel).length;
}).show();
var count=$(".leftlist li:visible").length;
document.cookie="incompletecount="+count;
})
})(jQuery)
jQuery(document).ready(function(){
jQuery('.chkbx').click(function(){
var cuser_id='<?php echo $current_user->ID;?>';
var m_val='0';
if(jQuery(this).is(':checked'))
{
m_val='1';
jQuery(this).parent().next("dd").addClass('strike');
}else
{
m_val='0';
jQuery(this).parent().next("dd").removeClass('strike');
}
var m_key=jQuery(this).attr('id');
jQuery.ajax({
type: "POST",
url: "<?php echo get_template_directory_uri(); ?>/ajax_get/",
data: { meta_key: m_key, meta_value: m_val},
beforeSend: function( ) {
jQuery(this).attr("disabled", true); }
})
.done(function( msg ) {
jQuery(this).attr("disabled", false);
});
});
});
Where the ajax_get.php has the following code:
<?php
require_once('../../../wp-load.php' );
wp();
if ( is_user_logged_in() ) {
$current_user = wp_get_current_user();
update_user_meta($current_user->ID, $_REQUEST['meta_key'],$_REQUEST['meta_value']);
echo $_REQUEST['meta_value'];
}
else{
echo'0';
}
?>
Basically you need to implement a database query, which will update all records, based on the new meta key, this can be done in your ajax_get.php file.
This is how you can do it.
Unfortunately your question is incomplete and I cannot give you more clues.
EDIT:
It seems to be an error in your code, check this line:
url: "<?php echo get_template_directory_uri(); ?>/ajax_get/",
should it be
url: "<?php echo get_template_directory_uri(); ?>/ajax_get.php" ?

Categories