简体   繁体   中英

isset() not working properly for dynamic form

I have a code for a Canteen Menu and cart system. After the user selects items from the menu and clicks on the purchase button, they get an Order Summary of sorts, which is dynamically coded as a form with an Order button acting like a submit button. When I use isset() in the php document to tell it what to do once Order is clicked, it returns true even when the form hasn't appeared, and there IS no submit button to click.

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

This gives me 'Hi' even when the user hasn't purchased anything, the order summary or the order button with the name 'ORDER' hasn't yet appeared. The following is my Javascript code for dynamically changing the cart to an Order Summary and back

function array(){
    title=document.getElementsByClassName("cafe")[1];
    alternate_title=`<br>
    <center><h1>Order Summary</h1></center>
    <br>`
    title.innerHTML=alternate_title;
    name=document.getElementsByClassName("cus_name")[0].textContent;
    console.log(name);
    order=[];
    var cartRows=document.getElementsByClassName('cart-items')
    for(var i=0;i<cartRows.length;i++){
        var cartRow=cartRows[i];
        var nameElement=cartRow.getElementsByClassName("item-name")[0];
        var name=nameElement.textContent;
        var quantityElement=cartRow.getElementsByClassName("quantity")[0];
        var quantity=parseFloat(quantityElement.value);
        item=[name,quantity];
        order.push(item);
    }
    var contents=`<form method="post"><div class="centered">`
    for(var i=0;i<order.length;i++){
        contents=contents+`<div class="cart-items" style="display: flex;">
        <div style="width:2em;">${i+1}.</div>
        <div><input type="text" value="${order[i][0]}" name="pdt_name[]"></div>
        <div><input type="number" value="${order[i][1]}" name="pdt_qty[]"></div>
        <div></div>
    </div><br>`;
    }
    contents=contents+`<br><center><input type="submit" name="ORDER" class="a" value="Order"></center></div></form>`;
    var half=document.getElementsByClassName("bill")[0];
    half.innerHTML=contents;
    
    document.getElementsByClassName("e")[0].addEventListener("click", goBack) ;
    function goBack(){
        title=document.getElementsByClassName("cafe")[1];
        alternate_title=`<br>
        <center><h1>Cart</h1></center>
        <br>`
        title.innerHTML=alternate_title;
        contents=`<div class="bg">
                
        <div class="all-items">
    
        </div>
    
        <hr>
    </div>
    <div class="eh"><h2><center>Total: <span class="total">Rs. 0</span></center></h2></div>
    <br>
    <center><input type="submit" value="Purchase" class="c"></center>
    </div>`
    var half=document.getElementsByClassName("bill")[0];
    half.innerHTML=contents;
    } 
}

Is there a reason for this? How can this be overcome?

EDIT: this answer by @Gideon Rosenthal has more simple solution.

$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';

if($pageWasRefreshed ) {
   //do something because page was refreshed;
} else {
   //do nothing;
}

If you wanna prevent same post data that executed after refresh you can use token on your form.
Not best solution , but it works.

<?php
// it need session to work
session_start();

// UUID from https://stackoverflow.com/a/2040279/10940544
// it doesn't matter how token should generate
// it just need to be different with the old one
function regenerateToken()
{
  $_SESSION["buy_token"] = sprintf(
    '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
    mt_rand(0, 0xffff),
    mt_rand(0, 0xffff),
    mt_rand(0, 0xffff),
    mt_rand(0, 0x0fff) | 0x4000,
    mt_rand(0, 0x3fff) | 0x8000,
    mt_rand(0, 0xffff),
    mt_rand(0, 0xffff),
    mt_rand(0, 0xffff)
  );
}

// generate token if there's no token yet
if (!isset($_SESSION["buy_token"])) {
  regenerateToken();
}

// do your backend stuff here :)
if (isset($_POST["submit"])) {
  if ($_POST["token"] == $_SESSION["buy_token"]) {
    regenerateToken();
    var_dump($_POST);
    // do something
  } else {
    // here is if token is not valid
    echo "form expired!";
  }
}
?>
<form action="" method="post">
  <input name="test">
  <input name="token" value="<?= $_SESSION["buy_token"]; ?>" hidden>
  <button name="submit">submit</button>
</form>

reference
UUID generation on PHP answer by @William

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM