'Update Total in checkout of Woocommerce with Ajax Request

Before asking question on SO, I searched a lot about what I needed to make a ajax request with WordPress. All my code and the request is working, but is not doing what I need it to do.

What I need to do is When I click at the buttom on checkout page "Novo Dependente", the information with the values to calculate total must update. "Total" value must be updated with a value which I defined at product post type page on admin panel. This value I already get, but the updating the value is real problem to me.

This is the page that I working.

This is the page that I working.

This is the form, that shows up when i click the button, when i Toogle the checkbox I need to add the second value to the Total, another request with ajax.

This is the form, that shows up when i click the button, when i Toogle the checkbox I need to add the second value to the Total, another request with ajax

And here my code goes Obs: it's a plugin.

Here is the php code.

public function add_total_value()
{

    if (! $_POST['action'] || $_POST['action'] !== 'add_total_value' ) :
        echo json_encode(
            array(
                'status' => 'failed',
                'message' => 'erro'
            )
        );
        wp_die();
    endif;

    $woocommerce;
    $quantidadeDependentes = $_POST['quantiaDependentes'];
    //$produto_valor = WC()->cart->total;



    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) 
    {
        $product = $cart_item['data'];

        $item_id = $cart_item['product_id'];

        $endereco_igual = get_post_meta( $item_id, 'adicional_mesmo', true);
        $endereco_igual = str_replace(',', '.', $endereco_igual);
        $endereco_igual = floatval( filter_var( $endereco_igual, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION ) );

        $produtoValor = floatval( get_post_meta( $item_id, '_regular_price', true) );
        $valorTotal = $produtoValor + ( $endereco_igual * $quantidadeDependentes );

        WC()->cart->total = $valorTotal;
        WC()->cart->calculate_totals();
        wc_price($valorTotal);

    }







    echo json_encode( 
        array(
            'status' => 'success',
            'valorTotal' => wc_price($valorTotal)
        ));

    wp_die();
}

My Ajax request

function contagemDependentes()
{
    $contagem = jQuery('.woocommerce-dependentes-contagem');
    var quantiaDependentes = jQuery('.woocommerce-dependentes-card').length;

    if ( quantiaDependentes <= 0 ) {
        var mensagemNumeroDependentes = 'Nenhum dependente informado';
    } else if ( quantiaDependentes === 1 ) {
        var mensagemNumeroDependentes = '1 dependente';
    } else {
        var mensagemNumeroDependentes = quantiaDependentes+' dependentes';
    }

    jQuery($contagem).html(mensagemNumeroDependentes);


        var quantiaDependentes = jQuery('.woocommerce-dependentes-card').length + 1;

    var dados = {
        action: 'add_total_value',
        quantiaDependentes: quantiaDependentes
    };

        jQuery.ajax({
            type: 'POST',
            url: custom_values.ajaxurl,
            data: dados,
            dataType: 'json',
            success: function(response) 
            {
                console.log(response);
                if (response.status === 'success')
                {

                    console.log(response.status);
                    console.log(response.valorTotal);
                    var html  = "<tr class='order-total'>";
                        html +=     "<th>Total</th>";
                        html +=     "<td>";
                        html +=             response.valorTotal;
                        html +=     "</td>";
                        html += "</tr>";


                    jQuery( '.order-total' ).remove();
                    jQuery( 'tfoot' ).append( html );



                    jQuery( 'body' ).trigger( 'update_checkout' );

                }
            }
        });

}


Solution 1:[1]

before function() in functions.php always must be such code

add_action('wp_ajax_your_function_name', 'your_function_name');
add_action('wp_ajax_nopriv_your_function_name', 'your_function_name');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jose Lora