Skip to content
Advertisement

getting html innertext in php

I want to get a innertext value in my html to store it in my php variable. So far I have this.

This is my html code. I want to get innertext value of < p > which will show a float number calculated by my Javascript.

<!-- Total Price -->
      <form method="post">
        <div class="total-price-container">
          Total Price: <p class="totalPrice"></p>
          <button type="buy" name="buybutton" onclick="buyButtonClicked()">BUY</button>
        </div>
      </form>

In my php code I have this.

include 'html/cart.html';

// when buybutton clicked, sends the totalprice to sql database
  if (isset($_POST['buybutton'])) {

    // This will get the value of <p> and store it in totalPrice.
    $totalPrice = $html->find("p[class=totalPrice]")[0]->innertext;

    $sql = "INSERT INTO transaction (date, total_price) VALUES (now(), $totalPrice)";

I get Undefined variable error. What am I doing wrong?

Advertisement

Answer

Ajax or Copy it to a hidden field on submit

$html->find("p[class=totalPrice]")[0]->innertext; is not something that works on normal form submission – it looks more like some scraping code.

document.getElementById("buyForm").addEventListener("submit",function() {
  const price = document.querySelector(".total-price-container .totalPrice")
    .innerText
    .replace(/[^0-9.-]+/g,"");
  document.getElementById("total").value = price;
})
<form method="post" action="cart.php" id="buyForm">
<input type="hidden" name="total" id="total" value="" />
  <div class="total-price-container">
    Total Price:
    <p class="totalPrice">€16.25</p>
    <button type="buy" name="buybutton">BUY</button>
  </div>
</form>

PHP:

 $totalPrice = $_POST['total']);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement