0

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?

4
  • what does buyButtonClicked() do? It needs to do Ajax or submit a form with the innerHTML copied to a form field Commented Jan 18, 2021 at 14:08
  • You have no action to your form Commented Jan 18, 2021 at 14:08
  • @mplungjan buyButtonClicked() only alerts a message. Commented Jan 18, 2021 at 14:09
  • @manqlele I have included my html file in php file. Doesn't that make an enough connection? Commented Jan 18, 2021 at 14:11

1 Answer 1

2

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']);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Thanks to you it is taking innerText value. I get this error message Error: INSERT INTO transaction (date, total_price) VALUES (now(), € 16.89), because my total_price must be a float number. Do you know how I convert € 16.89 to 16.89? Once again thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.