I cannot return to input the value of a PHP POST

Asked

Viewed 626 times

-2

I have a form with four numeric fields, ncr11, ncr22, ncr33 and ncr44. There is still another field in the form, ncr, that will receive a total value, which corresponds to the sum of all the first four fields. The sum I made with PHP and was informed in another question that should keep the action of the blank form and execute the code on the same page, however, when refreshing the page, my result field always turns blank.

What I would like to do is that when the user entered the values, the result field was automatically updated.

<?php
$crTot = "";
if($_POST){
    $cr1 = $_POST['ncr11'];
    $cr2 = $_POST['ncr22'];
    $cr3 = $_POST['ncr33'];
    $cr4 = $_POST['ncr44'];
$crTot = $cr1+$cr2+$cr3+$cr4;
echo $crTot;
}
?>

<form method="post" action="">
<div id="circulantes">
    <div class="ativocirculante" id="ativocirculante">
        <h2>ATIVO CIRCULANTE<input type="text" placeholder="R$ 0,00" id="ac" readonly/></h2>
        <h4>Ativo Errático (Financeiro) <input type="text" placeholder="R$ 0,00 aplicações" id="ae"/></h4>
        <h4>Disponíveis (Caixa e Bancos)<input type="text" placeholder="R$ 0,00" id="disp"/></h4>
        <h3>ACO<input type="text" placeholder="R$ 0,00" id="aco" readonly/></h3>
        <h4>Contas a receber<input type="text" placeholder="R$ 0,00" id="cr" name="ncr" value="<?php echo $crTot;?>" readonly/></h4>
        <h4 id="cr1">Até 30 dias<input type="text" placeholder="R$ 0,00" id="cr11" name="ncr11"/></h4>
        <h4 id="cr2">31 a 60 dias<input type="text" placeholder="R$ 0,00" id="cr22" name="ncr22"/></h4>
        <h4 id="cr3">61 a 90 dias<input type="text" placeholder="R$ 0,00" id="cr33" name="ncr33"/></h4>
        <h4 id="cr4">Acima de 90 dias<input type="text" placeholder="R$ 0,00" id="cr44" name="ncr44"/></h4>
        <h4>Estoque<input type="text" placeholder="R$ 0,00" id="est"/></h4>
        <h4>Adiantamento a Fornecedores<input type="text" placeholder="R$ 0,00" id="af"/></h4>
        <h4>Despesas antecipadas<input type="text" placeholder="R$ 0,00" id="da"/></h4>
</div>
  • 1

    Those sums in $crTot will not work well if what is written in the boxes follows the format R$ X,XX

  • Bruce, please read the [Ask] guide as soon as possible. I opened a meta debate to discuss the case of your other question, as it was not clear but was answered.

  • This page is to bring correct results ? But what is your script before this page, which brings "send" the data in POST ? Or actually, you would have to use GET if you bring in the URL

  • Can you please detail the error? What message does it give? what comes in return...

  • Basically, I am creating a user way by entering the values inside the inputs (ncr11 until ncr44) it returns the sum of these inside the input (ncr). The problem is that when I load the page and enter test values within the mentioned inputs, the "ncr" input is empty... When I use if (isset($_POST){...} the page returns Notice: Undefined index: ncr11 in C: xampp htdocs menuVertical apCirculantes.php on line 20 Notice: Undefined index: ncr22 in C: xampp htdocs menuVertical apCirculantes.php on line 21

  • The action of your form is not being pointed to any page. Or you are making the submission via JQuery?

  • It was being pointed to the page calculos.php, but was instructed to bring the code to before the form, by testing. That way, I left the null action

  • Bruce, do you want the result to appear in real time or just when a button is pressed?

  • In real time, that’s the idea.

  • I’ll take the liberty of editing your question again so it doesn’t occur like the other one. See how the issue will look and take as a basis for your future questions.

  • Okay Anderson, anything to help will be welcome. Thank you

Show 6 more comments

1 answer

1


1 - Set a fixed mask for the value fields, use the plugin jQuery Input Mask , or use input with type='number', but this does not work in multiple browsers, to lock a format for number recommend the plugin.

2 - Action blank indicates that you do not use jQuery/Ajax to submit and want it to send to the same page, then the PHP that receives the $_POST should be at the top of the archive.

3 - As I said in the '1', to work you need a standard, ie always 'RS10,00', or '10,00', or '10.00', no matter what format, what matters is that input always has the same format.

Assuming your input would have the format 'RS10.00', use str_replace() to remove the 'R$' and number_format() to format the string in a decimal number:

<?php

$crTot = "";
if($_POST){
    $cr1 =  number_format(str_replace('R$', '', $_POST['ncr11']), 2, '.', ' ');
    $cr2 =  number_format(str_replace('R$', '', $_POST['ncr22']), 2, '.', ' ');
    $cr3 =  number_format(str_replace('R$', '', $_POST['ncr33']), 2, '.', ' ');
    $cr4 =  number_format(str_replace('R$', '', $_POST['ncr44']), 2, '.', ' ');
    $crTot = $cr1+$cr2+$cr3+$cr4;
    echo $crTot;
}
?>

And to put that value inside the input (you did it right):

<input type="text" placeholder="R$ 0,00" id="cr" name="ncr" value="<?php echo $crTot;?>" readonly/>

How to update automatically with JS:

You need to first add some classnames identifiers to the elements below:

<input type="text" placeholder="R$ 0,00" id="cr" name="ncr" value="" class='ncrTot' readonly/>
<h4 id="cr1">Até 30 dias<input type="text" placeholder="R$ 0,00" id="cr11" name="ncr11" class='ncr11 ncr_value'/></h4>
<h4 id="cr2">31 a 60 dias<input type="text" placeholder="R$ 0,00" id="cr22" name="ncr22" class='ncr22 ncr_value' /></h4>
<h4 id="cr3">61 a 90 dias<input type="text" placeholder="R$ 0,00" id="cr33" name="ncr33" class='ncr33 ncr_value' /></h4>
<h4 id="cr4">Acima de 90 dias<input type="text" placeholder="R$ 0,00" id="cr44" name="ncr44" class='ncr44 ncr_value' /></h4>

Note that a classname 'ncr_value' has been added to the 4 fields in question.

Now, to put a mask that will keep a pattern to the value, let’s use the jqueryinputmask plugin, just put it inside the '<head>' from your page along with jQuery:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/jquery.inputmask.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.js"
              integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
              crossorigin="anonymous"></script>

Now, to apply the mask, insert the following code into your file:

$('.ncr_value').inputmask('decimal', {
                'alias': 'numeric',
                'groupSeparator': ',',
                'autoGroup': true,
                'digits': 2,
                'radixPoint': ".",
                'digitsOptional': false,
                'allowMinus': false,
                'prefix': 'R$ '
    });

If everything went right, at this point you will have input with format 'R$00.00'.

Now, to do the calculation, there are several forms, in the example, a loop will be used by the inputs, and giving a dynamic sum:

//Indica para efetuar a soma quando for pressionado um botão com foco no input, quando o valor for alterado, ou qunado o foco seguir em diante
$(document).on('keyup blur change','.ncr_value',function(){
        var v = 0;  
        //Inicia o loop pelos cmapos
        $('.ncr_value').each(function(b,c) {   
        if ($(c).val()) {
        //Remove o 'R$' para converter em numero
        var a = $(c).val().replace('R$','');
        //Susbtitui a virgula padrão de milhares por nada para somar corretamente
        var b = a.replace(',','');
        //Usa o += para somar os valores
        v += parseFloat(b);
        }
    });
    //Preenche o elemento com classname 'ncrTot' com o resultado da soma.
    $('.ncrTot').val('R$' + v.toFixed(2));
});

I tried to explain in a simple way a way to do this, I do not know if it became so simple, da to improve and much, follow an example working in fiddle:

https://jsfiddle.net/jd8zz2kb/1/

  • Perfect, I’ve already changed the way you suggested. I await further instructions.

  • @Bruceduarte gives a look you can understand now.

  • It worked perfectly, thank you very much.

Browser other questions tagged

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