B. Pereira
B. Pereira

Reputation: 75

Page reloads when I use document.write(onClick) in Firefox

I make a code for a basic calculator in PHP and I had to use JavaScript to show it on the screen. However, when I try to make any calculation in Firefox, the page reloads with blank code and only a 0 shows up.

In Google Chrome everything looks fine.

I tried put document.open() and document.close(), and this still works fine in Chrome, but nothing happens in Firefox.

Anybody have a solution for this?

This is my function:

<?php 
function calcular(){
  $n1 = isset($_POST["val1"])?$_POST["val1"]:0;
  $n2 = isset($_POST["val2"])?$_POST["val2"]:0;
  $op = isset($_POST["operacao"])?$_POST["operacao"]:1;

  switch ($op) {
    case 'subtracao':
      $res = $n1 - $n2;
      break;    

    case 'multiplicacao':
      $res = $n1 * $n2;
      break;

    case 'divisao':
      $res = $n1 / $n2;
      break;

    default:
      $res = $n1 + $n2;
      break;
  }

  echo $res;
}
?>

The code on the form:

<input type="text" name="resultado" value="<?php calcular(); ?>">
<input type="submit" name="botao" value="Calcular" onclick="document.open();document.write('<?php calcular(); ?>');document.close();">

Thanks!

Upvotes: 1

Views: 59

Answers (1)

Lincoln Tosi
Lincoln Tosi

Reputation: 86

You don't need JavaScript. Just keep your php function and this should work:

<?php
function calcular() {
    // your function...
}
?>
<form method="post">
    <p><input type="text" name="val1"></p>
    <p><input type="text" name="val2"></p>
    <p><input type="text" name="operacao"></p>
    <p><input type="submit"></p>
</form>
<div>
    <?php calcular(); ?>
</div>

Upvotes: 1

Related Questions