programing

WooCommerce ajax로 카트 업데이트

mytipbox 2023. 3. 9. 21:41
반응형

WooCommerce ajax로 카트 업데이트

woocommerce 웹사이트에서 카트 페이지를 변경하고 "카트 업데이트" 버튼을 삭제하고 다음 그림과 같이 제품 항목을 추가 및 삭제하는 2개의 버튼을 만들었습니다.

여기에 이미지 설명 입력

수량 버튼을 클릭했을 때 카트 업데이트 버튼을 눌러도 같은 기능을 호출하고 싶습니다.

이걸 위해 나는 에이잭스를 사용하지만 그것은 아무 소용이 없어요.

내 생애 첫 번째function.php파일:

  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;

제 jquery 파일에는 다음과 같은 내용이 있습니다.

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

다음 오류가 발생합니다.

Failed to load resource: the server responded with a status of 404 (Not Found)

로드하려고 하기 때문에my_website/cart/ajax_object.ajax_url.

잘 부탁드립니다!

다음 필수 프로세스를 잊어버렸습니다.

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

그 후, 「」를 취득합니다.ajaxurl" 및 "cart_ajax"에 있는 javascript 파일에 "url:":

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

Javascript 기능이 작동하지 않습니다.필요한 기능의 를 다음에 나타냅니다.

2016년 6월 출시된 WooCommerce 2.6.0 이후, WooCommerce 카트 페이지는 Update cart 버튼을 클릭한 후 Ajax를 사용하여 카트 합계를 업데이트합니다.

Ajax 콜을 직접 작성할 필요가 없어지고 Update cart 버튼에 할당된 콜을 사용할 수 있습니다.

무료 플러그인 Ajax Cart AutoUpdate for WooCommerce를 만들었습니다.제품 수량 변경 후 카트 페이지와 미니 카트를 업데이트하고 이 프로세스에 대한 커스터마이즈 옵션을 제공합니다.

가장 중요한 것은 업데이트 지연을 설정하는 것입니다.이 지연 시간 동안 사용자가 다시 수량을 변경하면 전체 기간으로 재설정됩니다.구현되지 않은 상태에서 증분 버튼을 클릭하여 수량을 1에서 10으로 변경하면 1이 아닌 9개의 Ajax 콜이 트리거됩니다.

JQuery 코드는 다음과 같습니다.js 파일에 저장하고 jQuery에 의존하여 큐잉하는 것을 권장합니다.그러면 jQuery가 지연됩니다.

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

언급URL : https://stackoverflow.com/questions/37710770/update-cart-with-woocommerce-ajax

반응형