dongtuji0992 2018-02-17 07:20
浏览 76

按钮操作不起作用

I'm working on an Online Store project with PHP and MySQL.

Lets say that in details.php page which contains all the information of a product, I have this:

<button type="button" name="cart_btn" class="formaction btn btn-fefault"><i class="fa fa-shopping-cart "></i>
    Add to cart
</button></br>

And at the same page I added this script as well:

$(document).ready(function(){
        $('.formaction').click(function(){
            var clickBtnValue = $(this).val();
            var ajaxurl = 'details.php',
            data =  {'action': clickBtnValue};
            $.post(ajaxurl, data, function (response) {
                // Response div goes here.
                alert("action performed successfully");
            });
        });
    });

And also this code:

if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_cart':
                add_cart();
                break;
            case 'select':
                select();
                break;
        }
    }
    function add_cart(){
        if(isset($_POST['cart_btn'])){
            $pro_id = $_POST['pro_id'];
            $ip = getIp();
            $add_cart = $pdo->prepare("INSERT INTO cart (pro_id,qty,ip_add) VALUES ('$pro_id','1','$ip')");

            if($add_cart->execute()){
                echo "<script>alert('adssadsad')</script>";
            }else{
                echo "<script>alert('Try Again')</script>";
            }
        }
    }

But the problem is, it does not work at all! I mean when you click on the button, it does not run these scripts...

So what is going wrong here guys, if you know please help me with that.. Thanks!

  • 写回答

1条回答 默认 最新

  • dsfh40613182 2018-02-17 07:38
    关注

    You need to remove this line

    if(isset($_POST['cart_btn'])){
    

    The button key => value does not get sent via AJAX.

    Also this line

    $pro_id = $_POST['pro_id'];
    

    will give null.

    You only send action via AJAX POST

    Template of how your data should look like

    data =  {'action': clickBtnValue, 'pro_id' : 'value_of_pro_id'};
    

    Also instead of sending javascript via your php script, send a better response of 1 or 0 for success or failure respectively. At the moment you display a success message regardless of whether the save was successful or not

    评论

报告相同问题?

悬赏问题

  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂