0
votes

How can I update cart content via AJAX after 'update cart' button click?

When I'm trying to use $fragments function, it always returns true... I've tryied use woocommerce hooks but fields was not refreshing via AJAX. I realy need a little help, because I'm stuck. I've tried everything... I belive that can be done via "add_action". Help? :)

add_action('woocommerce_checkout_after_customer_details','inputs_after_cart');

function inputs_after_cart($checkout) {

    global $woocommerce;
    $items = $woocommerce->cart->get_cart();

    $i = 1;

    foreach($items as $item => $values) { 
        $_product = $values['data']->post;
        $quantity = $values['quantity'];
        $x = 1;

        while ($x <= $quantity) {

         echo '<div class="col-12 refresh-tickets"><h3>' . $_product->post_title .  __(' - Bilet ' . $x . ' ') .'</h3>';


         $namevar = 'name'.$x;
         $emailvar = 'email'.$x;


         woocommerce_form_field($namevar , array(

        'type' => 'text',
           'label'      => __('Name'),
           'placeholder'   => _x('', 'placeholder', 'woocommerce'),
           'required'   => true,
           'class'      => array(''),
           'clear'     => true,
               ));

        woocommerce_form_field($emailvar, array(

        'type' => 'text',
           'label'      => __('E-mail'),
           'placeholder'   => _x('', 'placeholder', 'woocommerce'),
           'required'   => false,
           'class'      => array(''),
           'clear'     => true,
               ));

                echo '</div>';
                $x++;
            }

            $i++;
            } 

}
1
What in particular are you trying to update when you add an item to the cart?Andrew Schultz
As you see im trying to add woocommerce_form_field (name and email input) in dependence of quantity cart items. For each item add one field. On change quantity of items, number of inputs should be updated to current items count.WojtekMG
Look at this example, you can use the JS trigger "updated_cart_totals" stackoverflow.com/questions/39312360/…Andrew Schultz

1 Answers

1
votes

You can write scripts that listen to WooCommerce javascript trigger events and then run your own code when it's fired. Here the javascript trigger for the add to cart action.

$( document.body ).trigger( 'updated_cart_totals' );

Hook into that trigger using this javascript.

$( document.body ).on( 'updated_cart_totals', function(event){
    //Run your own code here, use AJAX to call a PHP function to create new inputs
    $.ajax({
        url : 'http://yourwesbite.com/wp-admin/admin-ajax.php',
        type : 'post',
        data : {
            action : 'the_function_that_creates_inputs'
        },
        success : function( data ) {
            // data contains HTML inputs to display
        }
    });
});