How to use PHP variables in JavaScript? [closed]

-2

I have a quantity variable, and I have two tags <a> that function as onclick and call the function myFunc1 or myFunc2 . One serves to increase the amount and another to decrease. to myFunc1 to decrease and to myFunc2 to increase.

<a onclick='myFunc1()' style='font-size:18px' id='diminuir' class='fa'>&#xf147;</a>

<script type="text/javascript">
  function myFunc1() {
    var oldValue = <?php echo json_encode($quantidade)?>;
    if (oldValue > 0) {
      var newVal = parseFloat(oldValue) - 1;
    } else {
      newVal = 0;
    }
    <?php echo json_encode($quantidade)?>; = newVal;
  }

  function myFunc2() {
    var oldValue = <?php echo json_encode($quantidade)?>;
    var newVal = parseFloat(oldValue) + 1;
    <?php echo json_encode($quantidade)?> = newVal;

    <?php echo json_encode($quantidade)?>; = newVal;
  }
</script>

I want the tags to increase and decrease the variable amount, and from what I've seen the only way I've seen to do this is with onclick, and to do the function I want to pass the variable quantity that is php, increase it with javascript and back to convert it to php

But this code is not working, is the problem of differentiating variables, tag or anything else?

    
asked by anonymous 20.06.2018 / 18:18

1 answer

1

Do this: type the following exactly in a page.php file,

<html>
  <head>
    <title>Minha pagina</title>
    <script
      src="https://code.jquery.com/jquery-2.2.4.min.js"integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
      crossorigin="anonymous"></script>
  </head>
  <body>
<?php
    $q = 0;
    if (isset($_POST) && isset($_POST['q'])) {
        echo "<h1>A sessão q no lado servidor vale {$_POST['q']}</h1>";
        $_SESSION['q'] = $_POST['q'];
        $q = $_SESSION['q'];
    }

    // Salva q em algum lugar.
    // salvar($q);
?>
    <form method="post" id="f">
      <label for="inc">Incrementa</label><input type="button" value="Aperte para incrementar" id="inc" /><br />
      <label for="dec">Decrementa</label><input type="button" value="Aperte para decrementar" id="dec" /><br />
      <label for="u">Valor no lado cliente:</label><input type="text" name="q" id="u" readonly="readonly" value="<?= $q ?>" />
    </form>
    <script type="text/javascript">
      $(function () {
        $('#inc').on('click', function () {
            var u = +$('#u').val();
            $('#u').val(++u);
            this.form.submit();
        });
        $('#dec').on('click', function () {
            var u = +$('#u').val();
            if (u) {
                $('#u').val(--u);
            }
            this.form.submit();
        });
      });
    </script>
  </body>
</html>

run and see the behavior.

    
20.06.2018 / 19:56