Calculate Quantity x Price and play value in input and session

Asked

Viewed 876 times

2

I am trying to play a calculation of total in an input and also in session in shopping cart that I am developing and am not succeeding, I will try to explain the problem I have.

The inputs are like this:

<div class="qty">

// QUANTIDADE
<?php if ( isset($_SESSION["quantidade"][$id]) && ($_SESSION["quantidade"][$id] != 0) ){ ?>
<input type="text" id="quantidade" name="quantidade" maxlength="10" value="<?php echo $_SESSION["quantidade"][$id] ?>" id_qtd="<?php echo $list['id_produto'] ?>"  />
<?php } else { ?>
<input type="text" id="quantidade" name="quantidade" value="<?php echo $QTD; ?>" class="input" id_qtd="<?php echo $list['id_produto']; ?>" />
<?php }  ?>&nbsp; x &nbsp;

// VALOR UNITÁRIO
<?php if ( isset($_SESSION["valor_unitario"][$id]) && ($_SESSION["valor_unitario"][$id] != 0) ){ ?>
<input type="text" id="valor_unitario" name="valor_unitario" maxlength="10" value="<?php echo $_SESSION["valor_unitario"][$id] ?>" id_unit="<?php echo $list['id_produto'] ?>"  />
<?php } else { ?>
<input type="text" id="valor_unitario" name="valor_unitario" value="<?php echo $QTD; ?>" class="input" id_unit="<?php echo $list['id_produto']; ?>" />
<?php }  ?>&nbsp; = &nbsp;                                      

SOMA TOTAL
<input type="text" id="valor_total" name="valor_total" value="<?php echo $_SESSION["valor_total"][$id]; ?>" 
id_total="<?php echo $list['id_produto']; ?>" />                                        

Each record, as quantidade and valor unitárioI am storing in session and they are registered even when I insert a new product, I do it to store them:

The calls are like this:


        // ATUALIZANDO QUANTIDADE
        $("input[name='quantidade']").blur(function(){  

            var sAcao = 'atualizar-quantidade';
            var sQuantidade = $(this).val();
            var sID_QTD = $(this).attr('id_qtd');           

            $.ajax({
                type: "POST",
                url: "atualizar-dados.php",             

                data: {
                    'acao' : sAcao,
                    'quantidade' : sQuantidade,
                    'id_qtd' : sID_QTD
                },              

                success: function(msg){
                    $(".ms").text(msg);
                }               
            });
        });

        // ATUALIZANDO O VALOR UNITÁRIO
        $("input[name='valor_unitario']").blur(function(){  

            var sAcaoUnit = 'atualizar-valor';
            var sValorUnitario = $(this).val();
            var sID_UNI = $(this).attr('id_unit');  

            $.ajax({
                type: "POST",
                url: "atualizar-valor.php",             

                data: {
                    'acaoUnit' : sAcaoUnit,
                    'valor_unitario' : sValorUnitario,
                    'id_unit' : sID_UNI
                },              

                success: function(msg){
                    $(".ms").text(msg);
                }               
            });
        }); 

    });

Amount:

    session_start();
    $acaoUnit = $_POST['acao'];

    if ( isset($acao) && $acao == 'atualizar-quantidade' ){
        $id = isset($_POST["id_qtd"]) ? $_POST["id_qtd"] : null;

        $_SESSION["quantidade"][$id] = $_POST['quantidade'];
        //echo $_SESSION["quantidade"][$id];    
    }   

Unit Value:

    session_start();
    $acaoUnit = $_POST['acaoUnit'];

    if ( isset($acaoUnit) && $acaoUnit == 'atualizar-valor' ){
        $id = isset($_POST["id_unit"]) ? $_POST["id_unit"] : null;

        $_SESSION["valor_unitario"][$id] = $_POST['valor_unitario'];
        // echo $_SESSION["valor_unitario"][$id];   
    }   

What I’m trying to do to keep the total sum:

window.onload = function() {
    $("input[name='valor_total']").focus(function() {

        $('.qty').each(function() {

            // console.log(this);

            var qtd = $(this).find('input[name=quantidade]').val()
            var val = $(this).find('input[name=valor_unitario]').val();         

            // QUANTIDADE TOTAL
            var total = parseFloat(qtd) * parseFloat(val);              

            $(this).find('input[name=valor_total]').val(total); 

            var sAcaoTotal = 'atualizar-total';
            var sValorTotal = total;
            // var sID_Total = $(this).attr('id_total');    

            // alert(sValorTotal);

            $.ajax({
                type: "POST",
                url: "atualizar-total.php",             

                data: {
                    'acaoTotal' : sAcaoTotal,
                    'valor_total' : sValorTotal
                    // 'id_total' : sID_Total
                },              

                success: function(msg){
                    $(".ms").text(msg);
                }   

            });



        });
    })
}

And the attempt to save the value in session:

    session_start();

    $acaoTotal = $_POST['acaoTotal'];

    if ( isset($acaoTotal) && $acaoTotal == 'atualizar-total' ){

        $id = isset($_POST["id_total"]) ? $_POST["id_total"] : null;

        $_SESSION["valor_total"][$id] = $_POST['valor_total'];
        // echo $_SESSION["valor_unitario"][$id];   
    }

For quantity and unit value it works, but for total it does not, it is doing the following: I insert a new product, it informs the quantity and unit value and when clicking on the total field the sum is made, but when inserting a new product the total adds up, but if clicking on the total field the value is calculated. I hope I didn’t make it complicated.

  • Unfortunately I could not understand what I meant, I think of some solutions already, however, to be sure, I would like you to explain better

  • Hello @Rafaelaugusto, I need to save the total value, I cannot keep it available, the quantity and unit value remain, but the total value does not.

  • Can be with JS?

  • If you help me @Rafaelaugusto, it’s on.

  • I’ll give you the idea to save, if you think it works in your case (because I didn’t understand very well to be sure), put a complete answer. Ever thought of using sessionStorage or localStorage? you store the value and can search to any mountain, on any page.

1 answer

0


You can use PHP itself in each unit value update and amount to persist the total in the session, saving even the extra AJAX call to the total value_value, since it changes whenever one of the other two is changed:

Quantity and total:

session_start();
$acaoUnit = $_POST['acao'];

if ( isset($acao) && $acao == 'atualizar-quantidade' ){
    $id = isset($_POST["id_qtd"]) ? $_POST["id_qtd"] : null;

    $_SESSION["quantidade"][$id] = $_POST['quantidade'];
    $_SESSION["valor_total"][$id] = ($_SESSION["valor_unitario"][$id] *  $_SESSION["quantidade"][$id]);
}  

Unit value and total:

session_start();
$acaoUnit = $_POST['acaoUnit'];

if ( isset($acaoUnit) && $acaoUnit == 'atualizar-valor' ){
    $id = isset($_POST["id_unit"]) ? $_POST["id_unit"] : null;

    $_SESSION["valor_unitario"][$id] = $_POST['valor_unitario'];
    $_SESSION["valor_total"][$id] = ($_SESSION["valor_unitario"][$id] * $_SESSION["quantidade"][$id]);
}   

This way you can return both the changed value (quantity or unit value) and the total value for the same input AJAX call and treat both at the same time in javascript.

  • Hello @nunks.lol, good morning, I made the nominee and still can not solve, thanks for the tip.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.