Woocommerce - Calculate shipping without reloading page by AJAX - php

I need to calculate the cost of shipping without reloading the cart page. I'm trying to do this via AJAX but I did not succeed.
I started the code below and could not continue
var $warp_fragment_refresh = {
url: wc_cart_fragments_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'get_refreshed_fragments' ),
type: 'POST',
success: function( data ) {
if ( data && data.fragments ) {
jQuery.each(data.fragments, function(key, value){
jQuery(key).replaceWith(value);
});
jQuery( document.body ).trigger( 'wc_fragments_refreshed' );
}
}
};
jQuery( function( $ ){
$('form.woocommerce-cart-form').on('submit', function (e)
{
e.preventDefault();
$(".btn-calc-ship").addClass("loading");
var ship_calc = window.location,
form = $(this);
$(".btn-calc-shipp").removeClass("loading");
});
});

Related

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).

two ajax responses in WP

I am using ajax to load data when clicking a link in WordPress.
The request returns the response 2 times in one click.
The Code:
add_action( 'wp_ajax_pt_add_to_compare', 'pt_add_to_compare_callback' );
add_action( 'wp_ajax_nopriv_pt_add_to_compare', 'pt_add_to_compare_callback' );
function pt_add_to_compare_callback() {
$response = do_shortcode('[aps_product_specs id="'.$_POST['id'].'"]');
echo $response;
exit;
}
and the Ajax Part is
$(document).on('click', '.aps-comp-results li a', function (e) {
e.preventDefault();
var link = $(this).attr('href');
var id = getQueryVariable(link, "id");
$.post({
url: ptobject.ajaxurl,
data: {
id: id,
action: 'pt_add_to_compare',
},
success: function (response) {
$('.comparison-row').append('<div class="col-md-4">' + response + '</div>');
}
});
});
So Why this code returns the response twice?

Wordpress AJAX call response 0

I'm tryng to set up a panel, this one
The menu on the top calls different ajax functions in order to display a thumb. Clicking on the thumb you can see the details in the last box of the panel.
I have this php functions
function GetPostPartner(){
$catPartner = "loop_pb_partner";
get_template_part($catPartner);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostPartner', 'GetPostPartner');
function GetPostEnte(){
$catEnte = "loop_pb_ente";
get_template_part($catEnte);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostEnte', 'GetPostEnte');
function GetPostColl(){
$catColl = "loop_pb_coll";
get_template_part($catColl);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostColl', 'GetPostColl');
function GetPostMedia(){
$catMedia = "loop_pb_media";
get_template_part($catMedia);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostMedia', 'GetPostMedia');
function GetPostDetails(){
$pb_details = $_POST['postURL'];
get_template_part($pb_details);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostDetails', 'GetPostDetails');
And those are called by these ajax functions
$(document).delegate('h4.homus-partners-global-ajax[data-pb- cat*=pb_partner]', 'click', function(event) {
event.preventDefault();
var pb_cat = "pb_partner";
var data = {
'action': 'GetPostPartner',
catURL : "loop_"+ pb_cat,
};
$.post(ajaxURL, data, function(response) {
$( 'ul.homus-partners-section-slide' ).html(response);
});
});
$(document).delegate('h4.homus-partners-global-ajax[data-pb-cat*=pb_ente]', 'click', function(event) {
event.preventDefault();
var pb_cat = "pb_ente";
var data = {
'action': 'GetPostEnte',
catURL : "loop_"+ pb_cat,
};
$.post(ajaxURL, data, function(response) {
$( 'ul.homus-partners-section-slide' ).html(response);
});
});
$(document).delegate('h4.homus-partners-global-ajax[data-pb-cat*=pb_coll]', 'click', function(event) {
event.preventDefault();
var pb_cat = "pb_coll";
var data = {
'action': 'GetPostColl',
catURL : "loop_"+ pb_cat,
};
$.post(ajaxURL, data, function(response) {
$( 'ul.homus-partners-section-slide' ).html(response);
});
});
$(document).delegate('h4.homus-partners-global-ajax[data-pb-cat*=pb_media]', 'click', function(event) {
event.preventDefault();
var pb_cat = "pb_media";
var data = {
'action': 'GetPostMedia',
catURL : "loop_"+ pb_cat,
};
$.post(ajaxURL, data, function(response) {
$( 'ul.homus-partners-section-slide' ).html(response);
});
});
$(document).delegate('li.homus-partners-section-single', 'click', function(event) {
event.preventDefault();
var pb_post_id = $(this).data('post-id');
var data = {
'action': 'GetPostDetails',
postURL : "single_pb_post_details",
post_id: pb_post_id
};
$.post(ajaxURL, data, function(response) {
$( '.homus-partners-detalis' ).html(response);
console.log(pb_post_id);
console.log(data.postURL);
console.log(response);
});
});
the response that I have is always 0 even if the console of the last ajax call here above return the right postid. You can find the whole project in this repo
https://github.com/wanbinkimoon/homus-web.git
in the code
function GetPostPartner(){
$catPartner = "loop_pb_partner";
get_template_part($catPartner);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostPartner', 'GetPostPartner');
instead of including the file by get_template_part paste the code here and then try

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

How to disable drag and drop and browse events while an ajax request is in process?

I want to prevent the user to stop selecting or drag and drop while the previous ajax request is in process.
How can i do this...
Here is the code js code :
#drag is the div id of drag and drop area
$( '#drag ' ).bind( 'dragover',function(event) {
event.stopPropagation();
event.preventDefault();
});
$( '#drag ' ).bind( 'drop',function(event) {
event.stopPropagation();
event.preventDefault();
if( upfiles == 0 )
{
upfiles = event.originalEvent.dataTransfer.files;
console.dir(upfiles);
upfiles = Array.prototype.slice.call(upfiles, 0);
}
else {
if(confirm( "Drop: Do you want to clear files selected already?" ) == true) {
upfiles = event.originalEvent.dataTransfer.files;
upfiles = Array.prototype.slice.call(upfiles, 0);
$('#fileToUpload').val('');
}
else
return;
}
$( "#fileToUpload" ).trigger( 'change' );
});
after clicking on upload button:
$("#upload_btn").click( function() {
if ( upfiles ) {
$( '#fileToUpload' ).trigger('upload'); // trigger the first 'upload' - custom event.
$(this).prop("disabled", true);
}
});
Here is the ajax request :
$( '#container' ).on( 'upload', '#fileToUpload' , function( ) {
if ( typeof upfiles[count] === 'undefined') return false;
var data = new FormData();
var fileIn = $( "#fileToUpload" )[0];
if( !upfiles )
upfiles = fileIn.files;
$(upfiles).each(function(index, file)
{
data.append( 'file'+index, file );
});
var request = $.ajax({
url: 'files.php',
type: 'POST',
data: data,
cache: false,
contentType: false,
processData: false,
beforeSend: function( ) {
$(".progressbar").show();
},
xhr: function() {
var xhr = $.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener( 'progress', showProgress, false);
}
return xhr;
},
success: function(data){
if( percentComplete <= 100 ) {
$('#pb div').animate({ width: '100%' }, { step: function(now) {
$(this).text( Math.round(now) + '%' );
}, duration: 10});
}
$('#uplcomp').append( data );
}
});
How can i prevent the user while the previous files upload is in progress.
Updated
ok got it upto some extent (but this is also not a good idea, user can add div back from the firebug and send files again)
i have used
$( document ).ajaxStart(function() {
$( "#total" ).remove();
});
and in ajax start :
$(document).ajaxStop( function( ) {
//how can i add div back say : add <div id='total'></div> after <div id='someid'></div>
});
Is there any possibility that i can stop second ajax request while the first ajax is in process?
Apart from enabling/disabling drag and drop while ajax is in progress, I believe a better solution will be to show an transparent or translucent overlay which covers that area and prevent the user from selecting any draggable.
For disabling/enabling using jquery:
Use $( "#total" ).draggable( "disable" ); inside beforeSend() function of ajax.
Use $( "#total" ).draggable( "enable" ); inside success() of function ajax
Using CSS:
demo: http://jsfiddle.net/lotusgodkk/GCu2D/184/
CSS:
.checked {
position:fixed;
top:0;
left:0;
right:0;
bottom:0;
background:#BFBFBF;
opacity:0.5;
text-align:center;
}
.checked div {
margin:0 auto;
top:50%;
left:50%;
position:absolute;
}
HTML:
<div class="checked">
<div>Please wait...</div>
</div>
Just toggle the hide/show during ajax
Use $('.checked').show(); in beforeShow() and $('.checked').hide(); in success()
Finally i have used
if($.active === 0)
{
call ajax
}
else
{
alert("please wait previous request is in process");
}

Categories