0

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?

  • Hi! Welcome to Stackoverflow. It's very hard to help you with hypothetical code. Please read through this page [https://stackoverflow.com/help/how-to-ask](https://stackoverflow.com/help/how-to-ask). – JohannesAndersson Oct 26 '20 at 17:23
  • 2
    Replace "Hi" with `var_dump($_POST);`. Lets see what you have there – Yevgen Oct 26 '20 at 17:28
  • array(3) { ["pdt_name"]=> array(2) { [0]=> string(5) "Latte" [1]=> string(7) "Macaron" } ["pdt_qty"]=> array(2) { [0]=> string(1) "2" [1]=> string(1) "1" } ["ORDER"]=> string(5) "Order" } Something like this – Adrita Bhattacharya Oct 26 '20 at 17:30
  • 1
    Are you loading a fresh page or do you happen to reload an already POSTed page? – brombeer Oct 26 '20 at 17:36
  • So, basically, it is giving me the items I purchased before I refreshed the page again. If I purchase other items, it gives me values for them... But I need isset() to function properly because I have to feed the proper values into mysql table – Adrita Bhattacharya Oct 26 '20 at 17:38
  • so, you want to prevent same post data that executed after refresh? – nouvist Oct 26 '20 at 17:48
  • Yes, I need it to have no data until order is clicked on – Adrita Bhattacharya Oct 26 '20 at 17:58
  • 1
    It would help others help you by reducing the amount of unnecessary code you paste into your question. – Charlie Oct 26 '20 at 18:23

1 Answers1

0

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

nouvist
  • 1,107
  • 10
  • 24
  • Here's what it says: "Notice: Undefined index: token in C:\xampp\htdocs\Canteen Automation System - Copy\cart.php on line 167 form expired!" And then it doesn't change when I order something again. – Adrita Bhattacharya Oct 26 '20 at 18:25
  • **Undefined index: token** happens because token was not send on request, it should be input named token on form. and, if token doesn't change you can move `regeneraeToken()` on before `if (isset($_POST["submit"])` closing tag – nouvist Oct 26 '20 at 18:32
  • Now it's giving me only "form expired". It has also printed "> near the Order summary... Can it be because I am doing this within Javascript code? – Adrita Bhattacharya Oct 26 '20 at 18:44