Variable value changing according to a select

Asked

Viewed 410 times

2

I got the following problem, guys:

I have a variable $soma_produtos = 0 (Picks up bank values through a foreach)

Picking up the foreach data would look something like this: $soma_produtos += $produto->getPreco();

Other $desconto = $soma_produtos * 0.05

And finally the $total = $soma_produtos - $desconto

The problem is this, I want the discount value to be changed (updated without refresh) according to a select I have (this without giving Submit) select is like this

<select class="modo-pagamento" id="modo_pagamento">
    <option value="1">Depósito bancário (5% de desconto)</option>
    <option value="2">Pag Seguro</option>
</select>

That is, if the select returns me 1, I use the discount the way I spent up there, if not, I do not pass any discount.

  • 3

    Post as your logic is in php.

  • But that’s basically it @Diegofelipe. I have the total variable that will receive the sum of the products listed ($soma_products) and also the discount... Discount may vary depending on the select option

  • The problem is that you are quoting php variables, but you have placed javascript tags. If logica is in php, you need to add here. Or is it javascript only?

  • No refresh this will have to be done on the client side, probably with JS. PHP runs on the server. A tip: try to ask the next questions already with all the details, because the edition you made completely changes the problem, and harms the answers given.

2 answers

3

Is this what you’re looking for?

<?php
    tem_desconto = 0;
    tem_desconto = $_POST["modo_pagamento"];
    $soma_produtos = 0
    if (tem_desconto == 1)
        $desconto = $soma_produtos * 0.05
    $total = $soma_produtos - $desconto
?>
  • That’s basically it. But I want the value the total value to change for the user without accuracy of a "refresh" on the page...

  • @Naldson In order for a part of the page to change without the rest being changed you will need to use a technique called AJAX. I advise you to take a look at Jquery a javascript library capable of producing this technique much easier.

1


As I said, it is recommended to separate the parts, leave the php act on the server, and then do the rest from what is received.

<form id="compra" method="POST">
<select name="produtos" class="produtos" id="produtos">
    <option value="1">Item 1 (10$)</option>
    <option value="2">Item 2 (50$)</option>
</select>
x <input type="number" min="1" value="1" name="quantidade" id="quantidade">
<select name="pagamento" class="modo-pagamento" id="modo_pagamento">
    <option value="1">Deposito bancario (5% desconto)</option>
    <option value="2">Pag Seguro</option>
</select>
</form>
<div id="visualiza">
<span class="desconto"></span>
<span class="valor-total"></span>
</div>

Outline the two tags span:

<style type="text/css">
#visualiza > span { display: block; }
</style>

Ajax request:

<script type="text/javascript">
$(document).ready(function() {
    $('#compra').on('change', function(){
        var modo = $('#modo_pagamento').val();
        var produto = $('#produtos').val();
        var quantidade = $('#quantidade').val();
        var desconto, total;
        //var dados = $(this).serializeArray();
        $.ajax({
            url: 'get.php',
            method: 'POST',
            dataType: 'json',
            data: {produto: produto, quantidade: quantidade, desconto: modo},
            success: function(data){
             total = 'Total: ' + data.total +'$';
             desconto = 'Descontos: (' + data.perc_desconto + '%) pelo '+ data.resp_desconto;
             $('.valor-total').html(total); 
             $('.desconto').html(desconto);
             },
            error: function(i){ alert('erro'); }
        });
    });
});
</script>

Finally, the script php to operate on the server-side, and returns the values according to the data you are given, to be later organized without needing the php.

header("Content-Type: application/json; charset=utf-8;");

# produtos existentes
$produtos = array(
    1=> array('nome'=>'item1', 'preco'=>10),
    2=> array('nome'=>'item2', 'preco'=>50) 
    );
# descontos existentes  
$descontos = array(
    1=> array('nome'=>'Deposito bancario', 'perc'=>5),
    2=> array('nome'=>'Pag Seguro', 'perc'=>0)
    );  

# requisiçoes   
$produto = isset($_POST['produto']) ? $_POST['produto'] : false;
$quantidade = isset($_POST['quantidade']) ? $_POST['quantidade'] : false;
$c_desconto = isset($_POST['desconto']) ? $_POST['desconto'] : false;

# reset dos valores
$nome = $r_desconto = "";
$total = $preco = $p_desconto = 0;

if($produto):
    $nome = $produtos[$produto]['nome'];
    $preco = $produtos[$produto]['preco'];
    $total = $preco * $quantidade;
    if($c_desconto):
        $p_desconto = $descontos[$c_desconto]['perc'];
        $r_desconto = $descontos[$c_desconto]['nome'];
        $total = $total - ($total * $p_desconto/100);
    endif;  
endif;

# organizar a saida
$retorno = array(
    'total'=>$total,
    'produto'=>$nome,
    'preco'=>$preco,
    'quantidade'=>$quantidade,
    'perc_desconto'=>$p_desconto,
    'resp_desconto'=>$r_desconto
    );
/*  
print $nome . " (".$preco."$) " . " x " . $quantidade;
print "<br/>";
print "total: " . $total;
print "<br/>";
print "descontos: " . $p_desconto . "% pelo " . $r_desconto;
*/

# saida json:
print json_encode($retorno);
  • Perfect! Thank you!

  • 1

    You’re welcome, it’s a question of knowing, how do you want the returned values to be displayed.

Browser other questions tagged

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