简体   繁体   中英

Why ajax request isn't sending all the data?

I'm working in a ecommerce with wordpresss and woocommerce, im adding to the shop page and category pages buttons that display the sizes for each product. with this code inside the theme function:

function woocommerce_variable_add_to_carts() {
   global $product, $post;
   $variations = $product->get_available_variations();
   $product_sku = $product->get_sku();

   $out = '<ul class="iconic-was-swatches iconic-was-swatches--loop iconic-was-swatches--text-swatch   iconic-was-swatches--square">';
   foreach ($variations as $key => $value) {
    if (!empty($value['attributes'])) {
        foreach ($value['attributes'] as $attr_key => $attr_value) {
            $out .= '<li><a id="'.esc_attr($post->ID).'" data-quantity="1" data-product_id="'.esc_attr($post->ID).'" data-product_sku="'.$product_sku.'" class="iconic-was-swatch iconic-was-swatch--follow iconic-was-swatch--text-swatch add_to_cart_button">';
            $out .= $attr_value . '</a></li>';
        }
    }
}
$out .= '</ul>';
echo $out;
  }

    add_action('woocommerce_before_shop_loop_item_title', 'woocommerce_variable_add_to_carts');

The idea is that when the users click in one of those sizes buttons the product is added to the cart directly in that page (shop page, category page). I made a custom endpoint to solve that from the answer provided here . I call the ajax function in the js file that Contains this:

$('.add_to_cart_button').on('click',function(){

      jQuery.ajax({
            url: WC_VARIATION_ADD_TO_CART.ajax_url,
            type: "POST",
            data: {
                action : "customAdd_to_cart",
                product_id : "697",
                variation_id : "707",
                quantity : 1,
                variation : {
                    size : "s",
                    color: "pink"
                }
            },
            success: function(){
                alert('Ajax Success ');
            }
        });

    });

(i'm using a specific product_id and variation_id for testing) then i add the callback function in the themes function page to add the products to the cart :

function customAddToCart() {
ob_start();
try {

    $product_id        = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $data['product_id'] ) );
    $quantity          = empty( $data['quantity'] ) ? 1 : wc_stock_amount( $data['quantity'] );
    $variation_id      = isset( $data['variation_id'] ) ? absint( $data['variation_id'] ) : '';
    $variations        = $variation_id ? (array) get_variation_data_from_variation_id( $variation_id ) : null;
    $product_status    = get_post_status( $product_id );
    $passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $variations, $cart_item_data );

    if ( $passed_validation && WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variations ) && 'publish' === $product_status ) {

        do_action( 'woocommerce_ajax_added_to_cart', $product_id );

        $res = getCartFragments();

    } else {

        $res = array(
            'error' => true
        );

    }

    return $res;

} catch (Exception $e) {
    return new WP_Error('add_to_cart_error', $e->getMessage(), array('status' => 500));
}
}

   add_action( 'wp_ajax_nopriv_woocommerce_add_variation_to_cart', 'customAddToCart' );

all this seems to work fine because doesn't give any error in console but the problems is that the variation Size in not added with the product that is selected just add the product. I dont know why this is happening, i even add an alert in the ajax success function

alert('Ajax Success ');

and that alert is displayed but the data it seems is not been sending like it should.

i want to know what i'm missing in any of this codes or it could be the js file and his location or i need to send another value in the a> builded in the first function above. i have try a lot things but the behavior still the same.

A quick scan over your code and I've noticed that the action you are calling with ajax is not correct. It should be woocommerce_add_variation_to_cart not customAdd_to_cart . Also it is common practice to use wp_send_json (or the more specific wp_send_json_success and wp_send_json_error functions) at the end of your ajax callback function so that you get a readable and sensible response in jQuery. Check out the following link if you have not used it before:

https://codex.wordpress.org/Function_Reference/wp_send_json

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM