Home > database >  How to pass value from html element to php element
How to pass value from html element to php element

Time:09-30

i want to pass the value of an html element to a php element example:

<p id="test">Hello</p>

<?php>
$demo = $_POST['test'];
echo $demo;
?>

so when i run the php the Hello will be printed.

Thank you in advance.

CodePudding user response:

You can try this example hope it works

<form action="" method="post">
<input type="number" id="forderr" name="forder" min="0" max="1" required><br>
<button name="update">UPDATE</button>
    <?php
 $order = $_POST["forder"];
 echo $order;
    ?>

CodePudding user response:

You may use form controls or AJAX based APIs such as fetch or XMLHttpRequest to transfer data from your web client to server. In your case, considering <p id="test">Hello</p> is not a form control, we should utilize an API (such as fetch) to transfer data when some specific action (such as clicking on the element itself) has been triggered as below:

<html lang="en">
  <body>
    <p id="test">Hello</p>

    <script>
      const endpoint = "https://EXAMPLE.COM/process";

      document.querySelector("#test").addEventListener("click", function(e) {
        fetch(endpoint, {
          method: "POST",
          body: JSON.stringify({
            test: this.innerText,
          }),
        }).then(function(response) {
            // handle if was successful
        }).catch(function(err) {
            // handle if was erroneous 
        });
      });
    </script>
  </body>
</html>

Now you can handle the transmitted value using $_POST on your server side.

However if you insist on using <p> and avoiding fetch (or similar interfaces), you might want to use a hidden control field and bind its value to value of your specific non-control element (here, <p>...</p>). Below does the job as described and only when paragraph is clicked, its innerText will be set as the value for test form control field; then form will be submitted automatically:

<html>
  <body>
    <p id="test">Hello</p>

    <form method="POST" id="hidden-form">
      <input type="hidden" name="test" id="test" value="" />
    </form>

    <?php
        if (isset($_POST['test'])) {
            echo $_POST['test'];
        }
    ?>

    <script>
      document.querySelector("#test").addEventListener("click", function (e) {
        document
          .querySelector("#hidden-form #test")
          .setAttribute("value", this.innerText);

        document.querySelector("#hidden-form").submit();
      });
    </script>
  </body>
</html>
  • Related