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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog