How to use PHP variables in Javascript?

Asked

Viewed 64 times

-2

I have a quantity variable, and I have two tags <a> who function as onclick and call the function myFunc1 or myFunc2. One serves to increase the amount and the other to decrease. myFunc1 to decrease and 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 saw the only way I saw to do this is with onclick, and to make the function I want to pass the variable amount that is php, increase it with javascript and convert it back to php

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

  • 2

    Explain in words what you tried to do there, because the code made no sense.

  • 3

    If you are on a php page, the code var oldValue = <?php echo json_encode($quantidade)?> will work, but this other code does not make sense <?php echo json_encode($quantidade)?> = newVal. Have you thought about what will appear in the middle of the code javascript? something like 1 == newVal, and what it would do?

  • @Andersoncarloswoss I’ve edited there

  • 5

    But do you want to increase/decrease the value in JS and play it in the PHP variable? That’s not possible. Read on frontend and backend to better understand. One runs on the client side; the other on the server. The only way they can communicate is via messages via a communication protocol (HTTP, in general). If you want to do JS converse with PHP, use AJAX.

  • I want the <a> tags to increase and decrease the variable amount, and from what I saw the only way I saw to do this is with onclick, and to make the function I want to pass the variable amount that is php, increase it with javascript and convert it back to php

  • 1

    Are you showing the amount somewhere on the page? As Anderson Carlos Woss said, to pass the new amount to PHP you have to send that value to the server, and for that you can use AJAX. If you want to visually change the amount on the page, this is possible with Javascript only, but you will have to send it to the server at some point for PHP to know this new value.

  • @Exact yes milk I want to change the value of the variable, not just visually

  • edshewa, what you want is not possible this way. To increase the value of your variable in PHP you need to make a request to the server (PHP) which will be responsible for increasing this value.

  • 2

    You’ll have to follow Anderson Carlos Woss' suggestion then. Or if you want suggestions on which way to go, you need to put more information in the question. You can figure out what you want to do, and with the code you have, it’s not possible. But in more detail someone can help you find the right path.

  • 2

    Another thing for you to study: HTTP does not retain status (is stateless). So, what will PHP do with the new value?

  • As an example, when you are looking at a shopping cart you have the items and quantity. Sometimes you can change this amount, and sometimes also with buttons, but for later the server know the new value, there is a button that will submit these new amounts to the server. For example, the fields like this, https://en.helpforsite.com/image/cache/catalog/products/ajax_quantity_for_journal2_cart-1280x1280.png and then there would be a button that you didn’t see there to send to the server.

  • @Milk like a button you can’t see?

  • It is not seen in the link image, but it would be visible to those who see the page. This image is just an example.

  • Another question in the same style: https://answall.com/q/28673/132

Show 10 more comments

1 answer

1

Do it like this: write exactly the following on a.php page,

<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>

execute and see the behavior.

Browser other questions tagged

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