weixin_33738555 2018-12-23 22:43 采纳率: 0%
浏览 22

yii2购物车ajax

I want to modify existing shopping cart in yii2, so it wouldn't reload the page, means make it work by ajax. Current cart looks like:

 <form method="post" id="form-prodtobuy-<?= $p->id ?>" action="<?= \Yii::$app->urlManager->createUrl(["site/cart"]) ?>">
 <input type="hidden" name="<?= Yii::$app->request->csrfParam; ?>" value="<?= Yii::$app->request->csrfToken; ?>" />
 <input type="hidden" name="task" value="update" />
 <input id="<?= $p->id ?>" class="form-control buy-input" name="product[<?= $p->id ?>]" value="<?= Purchase::getCartValue($p->id) ?>" data-id="<?= $p->id ?>" placeholder="0">
 <button class="btn btn-primary" type="submit">Buy <i class="glyphicon glyphicon-shopping-cart"></i></button>
 </form>

It works properly, but reloads the page.

var_dump($_SESSION); after that looks like:

 array(2) { ["__flash"]=> array(0) { } ["products"]=> array(3) { [2958]=> string(1) "2" [2959]=> string(1) "1" [2581]=> string(1) "1" } }

My obvious solution is to add e.preventDefault() on submit event as follows:

 $(document).on('submit', '[id^=form-prodtobuy-]', function(e) {
 e.preventDefault();
 var someVar = $('#someInput').val();
     $.ajax({
        type: "post",
        url: "<?php echo \Yii::$app->urlManager->createUrl(["site/cart"]) ?>",
        data: {???:someVar},
        .....................
     });
 });

What should be in ajax 'data'?
Where or how is it possible to get names of variables to set session properly?

  • 写回答

1条回答 默认 最新

  • weixin_33704234 2018-12-23 23:07
    关注

    In ajax "data" put form seralization output.

    Take care that I've used heredoc format, so last EOT_JS must not have spaces before it.

    $urlForm = \Yii::$app->urlManager->createUrl(["site/cart"]);
    
    $this->registerJs( <<< EOT_JS 
    
        $(document).on('submit', '[id^=form-prodtobuy-]', function(e) {
            e.preventDefault();
    
            var formData = $(this).serialize();
    
            $.ajax({
                type: "post",
                url: "{$url}",
                data: formData,
                function(data) {
                    console.log('form submit output');
                    console.log(data);
                }
            });
        });
    
    EOT_JS
    );
    
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘