• I am customizing the notices on my site. I ran into a problem on the single product page. When the add to cart button is clicked, the form data is send to WordPress through AJAX (it took me a while to discover the code is in woo-ajax-add-to-cart.min.js). The response is not used, only passed to the added_to_cart event. BTW I wonder how this works as response.fragments is passed as variable, but this variable does not exist in the response from the POST.

    The wc_fragment_refresh event is also triggered. I have added a notices fragment to the woocommerce_add_to_cart_fragments filter and this works after most ajax calls, but not on the single product page.

    So, what’s the difference? I noted this is the only ‘add to cart’ button that uses a form. As a form is posted, the response is a complete HTML page (including the success or error notice). Apparently all notices are cleared in the back-end afterwards, because the wc_fragment_refresh event results in a fragments without notices.

    So, I was wondering I have to change something in the background to preserve notices, so they would be passed and displayed on the wc_fragment_refresh event.

    As the update cart button on the cart page also submits a form through AJAX, I analysed that code (in cart.js). I noted the post is made in a similar way. I have not (found and) analysed the php code that generates the response yet. The response is nonetheless similar (a complete HTML page including). However in this case the response is actually used: the form, cart-totals and notices are extracted from the response and then displayed. In this case the wc_fragment_refresh event is also triggered and the response does not contain any notices. However, it’s no problem for this page as they were already extracted from the response.

    The question is: why is the response from the form post disregarded?

    Now I have planned to modify (a copy of) the script to make it work (just a blueprint based on the code in cart.js):

    success: function( response ) {
    update_wc_div( response, preserve_notices );
    }

    var update_wc_div = function( html_str, preserve_notices ) {
    var $html = $.parseHTML( html_str );
    var $notices = remove_duplicate_notices( $( ‘.woocommerce-error, .woocommerce-message, .woocommerce-info’, $html ) );

    // Display errors
    if ( $notices.length > 0 ) {
    show_notice( $notices );
    }
    show_notice will be a function that prepends the notices to a existing wrapper.

    Any other thoughts?

Viewing 4 replies - 1 through 4 (of 4 total)
Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Add to cart function on single product page’ is closed to new replies.