0

Am trying to get the shipping packages with ajax but its always returning empty value.

same issue while trying to call get the zones with: WC_Shipping_Zones::get_zones();

am using the same code in woocommerce_checkout_before_order_review and its working without any issue!

function jsforwp_add_like() {

  check_ajax_referer( 'jsforwp_likes_nonce' );

  $packages    = WC()->shipping->get_packages();

    if(empty($packages)){
        $check = 'empty';
    }else{
        $check = $packages;
    }
    $success = true;
  if( true == $success ) {
    $response['type'] = 'success';
    $response['zone'] = $check;

  }

  $response = json_encode( $response );
  echo $response ;
  die();

}
add_action( 'wp_ajax_jsforwp_add_like', 'jsforwp_add_like' );
add_action( 'wp_ajax_nopriv_jsforwp_add_like', 'jsforwp_add_like' );

My javascript

add_action('wp_footer','my_custom_ajax');
function my_custom_ajax(){
?>
<script>
(function($){

  $( document.body ).on( 'updated_checkout', function(){
    $.ajax({
      type : 'post',
      dataType : 'json',
      url : jsforwp_globals.ajax_url,
      data : {
        action: 'jsforwp_add_like',
        _ajax_nonce: jsforwp_globals.nonce
      },
      success: function( response ) {
         if( 'success' == response.type ) {
            console.log( response );
         }
         else {
            console.log( 'Something went wrong, try logging in!' );
         }
      }
    });

  } );

} )( jQuery );
</script>
<?php
}

returned value

{type: "success", zone: "empty"}
2
  • You can't get packages without calculating shipping. I am not sure what is the purpose of getting packages in your code, your code seems correct but your logic is wrong. Commented Sep 13, 2022 at 6:53
  • @VijayHardaha I have free shipping progress bar which is hooked in 'woocommerce_checkout_before_order_review' and my amount for free shipping is different based on location. so its not updating when address changed. I solved it by hooking jQuery in 'woocommerce_review_order_after_shipping' that updates the elements html. Commented Sep 14, 2022 at 10:56

0

Browse other questions tagged or ask your own question.