dqudtskm49788 2013-10-29 14:01
浏览 16
已采纳

表单操作在不单击提交的情况下运行

I have a page where you view what is in your cart (a work in progress obviously) and there is a button to clear your cart, and it works, but moving to another page in the site, whether by clicking a link or typing in the address bar, runs the form action. It also does it on the product page to add to the cart. How do I stop this happening so the action only runs when the button is pressed?

<div id="">
     <?php echo "You have " . $_SESSION['cartItems'];
       if($_SESSION['cartItems'] == 1){
        echo " item";
       } else {
        echo " items";
       }
       echo " in your cart amounting to $" . $_SESSION['cartPrice'];?>
       <form action="<?php session_destroy();?>"><input type="submit" value="Clear Cart"></form>
</div>
  • 写回答

2条回答 默认 最新

  • douchi0638 2013-10-29 14:06
    关注

    After some time I undestand what you want to do. You can't destroy the session in action attribiute but you can put in action attribute the page where session will be destroyed

    destroy.php

    <?php
    session_start();
    session_destroy();
    echo 'destroyed';
    
    ?>
    

    Your main file

    <div>
     <?php 
       echo "You have " . $_SESSION['cartItems'].($_SESSION['cartItems'] > 1 ? 'items' : 'item');
       echo " in your cart amounting to $" . $_SESSION['cartPrice'];?>
       <form action="destroy.php"><input type="submit" value="Clear Cart"></form>
    </div>
    

    You can also put in action ="" and use some hidden param and check if it should be destroyed for example:

    One file solution:

     <div>
     <?php 
       session_start();
       if(isset($_POST['destroy']) && $_POST['destroy'] == 1) session_destroy(); //destroying session
    
       echo "You have " . $_SESSION['cartItems'].($_SESSION['cartItems'] > 1 ? 'items' : 'item');
       echo " in your cart amounting to $" . $_SESSION['cartPrice'];?>
       <form method="POST" action="">
          <input type="submit" value="Clear Cart"><input type="hidden" value="1" name="destroy">
       </form>
    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 html5+css有人可以帮吗?
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?