How to display the value of a variable in a modal bootstrap with PHP?

Asked

Viewed 2,210 times

0

I have a form which makes a calculation, inserts it into the database and returns the value through a alert.

I would like to replace this message from alert by a modal.

HTML

<form method="post" action="#">
<input type="hidden" name="acao" id="acao" value="cadastrar"/>

<input type="text" name="alt" id="altura" required><br><br>
<input type="text" name="peso" id="peso" required><br><br>

PHP

function calcularIMC($altura,$peso){
 $imc = 0;
   if($altura >0 && $peso >0){
     $imc = $peso / ($altura * $altura);
   }

 echo '<script>';
 echo 'alert("'.$imc.'");';
 echo '</script>';
}

I tried to do it this way: - I added the code php after the tag </html>; - I added the variable responsible for the calculation: $imc; - I linked the button Enviar with the modal.

  <form method="post" action="#">
    <input type="hidden" name="acao" id="acao" value="cadastrar"/>

    <input type="text" name="alt" id="altura" required><br><br>
    <input type="text" name="peso" id="peso" required><br><br>
    <button type="submit" id="Enviar" data-toggle="modal" data-target="#myModal">Enviar</button>
 </form>

        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">Modal title</h4>
          </div>
          <div class="modal-body">
           <?php echo'.$imc.';?>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
          </div>
        </div>
      </div>
    </div>
   </body>
 </html>

PHP

<?php
      function calcularIMC($altura,$peso){
    $imc = 0;
    if($altura >0 && $peso >0){
        $imc = $peso / ($altura * $altura);
     }   
    return $imc;
    }
 ?>

With that, when I click the button Enviar (with all fields empty), it opens the modal and displays the '.$imc.' like String. When I enter the data and click on the button Enviarthe window becomes opaque (beginning of the modal effect) and quickly returns to normal. I believe that the modal is being called, but somewhere along the way he closes.

How can I fix this?

  • 1

    A little question before... Why are you using this much echo? Really think it necessary?

  • @Lucashenrique, no. I was doing it wrong. I made some changes to the code, see the question again please :)

  • Are you using some framework to build your solution or are you doing it in "raw php" anyway? because from my experience with PHP and web, either you mount this on JS or already deliver the result as a view...

3 answers

1

Single quotes do not accept variables:

 <?php echo'.$imc.';?>

You messed up because of this:

 echo 'alert("'.$imc.'");';

Actually simple quotes there are "concatenating" only, I believe what you want is this:

<form method="post" action="#">
    <input type="hidden" name="acao" id="acao" value="cadastrar"/>

    <input type="text" name="alt" id="altura" required><br><br>
    <input type="text" name="peso" id="peso" required><br><br>
    <button type="submit" id="Enviar" data-toggle="modal" data-target="#myModal">Enviar</button>
</form>

<?php

function calcularIMC($altura,$peso){
 $imc = 0;
   if($altura >0 && $peso >0){
     $imc = $peso / ($altura * $altura);
   }

   return $imc;
}
?>

<!-- esta if verifica se veio do POST com isset -->
<?php if (isset($_POST['altura'], $_POST['peso'])): ?>

<?php
//Calcula IMC e adiciona a variavel
$imc = calcularIMC($_POST['altura'], $_POST['peso']);
?>

    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
       <?php echo $imc;?>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

<!-- encerra a IF -->
<?php endif; ?>

0

testing.php:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
        <title>Example</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
        <script>
            $(function () {
                //Comportamento do botao de envio
                $('#submit').click(function () {submit();});
                //Alteracao do comportamento do formulario de envio
                $("#form").submit(function (e) {e.preventDefault();});
            });
            //Funcao que faz o request
            function submit() {
                //Envia um request POST
                $.post(
                    $("#form").attr("action"),//Captura a action do FORM
                    $("#form").serialize(),//Captura os dados do FORM
                    //Captura a resposta do PHP
                    function (resp) {
                        //Passa a resposta pro corpo do MODAL
                        $('#modal-body').html(resp);
                        //Mostra o MODAL
                        $('#myModal').modal('show');
                    }
                );
            }
        </script>     
    </head>
    <body>
        <nav class="navbar"></nav>
        <div class="container">
            <div class="col-lg-5">
                <form action="testing.resp.php" id="form">
                    <input type="hidden" name="acao" id="acao" value="cadastrar"/>
                    <input type="text" name="altura" id="altura" value="1.75" required><br><br>
                    <input type="text" name="peso" id="peso" value="86" required><br><br>
                    <button class="btn btn-primary" type="button" id="submit">Enviar</button>
                </form>
            </div>
            <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" id="myModalLabel">Resultado do c&aacute;lculo</h4>
                        </div>
                        <div class="modal-body alert alert-success" id="modal-body"></div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

testing.resp.php:

<?php

if($_POST['altura']){$altura = $_POST['altura'];} else {$altura = NULL;}
if($_POST['peso']){$peso = $_POST['peso'];} else {$peso = NULL;}

function calcularIMC($altura, $peso) {
    $imc = 0;
    if ($altura > 0 && $peso > 0) {
        $imc = $peso / ($altura * $altura);
    }
    return $imc;
}

# Fazer inclusao dos dados no banco aqui

echo calcularIMC($altura, $peso);

0





Send
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
       <?php
      $text=$_REQUEST['$imc'];
      echo $text;?>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

  • Gives the same result as my rsrs code. The screen fades (as it will open the modal) and back to normal quickly :/

Browser other questions tagged

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