0

我正在开发一个有Apply Coupon表单的 CakePHP 3 项目。

我想使用 Ajax 应用优惠券。

优惠券形式的视图是

<?= $this->Form->create(null, [
  'url' => ['controller' => 'Coupons', 'action' => 'checkCoupon'],
  'name' => 'checkCoupon'
]) ?>
<?= $this->Form->input('coupon_code', [
  'type' => 'text',
  'placeholder' => 'Apply Coupon Code',
  'label' => false
]) ?>
<?= $this->Form->submit('Apply Coupon') ?>

中的checkCoupon动作CouponsController

public function checkCoupon()
{
  $this->request->onlyAllow('ajax'); // No direct access via browser URL

  if ($this->request->is('post')) {
    $couponCode = $this->request->data['coupon_code'];
    $couponCheck = $this->Coupons->find('all', [
      'conditions' => [
      'coupon_code' => $couponCode
      ]
    ]);
    if ($couponCheck->count() === 1) {
       $coupon = $couponCheck->first();
       $valid_till = $coupon->valid_till;
       $dt = new Time($valid_till);
       $date = $dt->format('Y-m-d');

       if ($date >= date('Y-m-d')) {
         echo 'Coupon is Valid. Discount of '.$coupon->value.'has been applied';
       } else {
         echo 'Coupon is Expired';
       }
    } else {
       echo 'This is not a valid coupon code';
    }
  }
}

我希望$coupon->valueand$coupon->id被检索并添加到结帐链接中

<?= $this->Html->link(__('Confirm Checkout'), ['controller' => 'ServiceRequests', 'action' => 'confirmCheckout', $service->id, $primaryAddressId, $serviceArea->id, $coupon->id], ['class' => 'btn btn-block btn-success']) ?>

Apply Coupon表单正在运行checkout表单RequestsController 也运行良好。我已经通过删除onlyAllow('ajax')行和打印check_coupon.ctp视图中的值来检查它。

我怎么能用 Ajax 做到这一点?

编辑 2:checkout.ctp

<div class="form-info coupon">
  <?= $this->Form->create(null, [
    'url' => ['controller' => 'Coupons', 'action' => 'ajax_checkCoupon'],
    'name' => 'checkCoupon',
    'id' => 'checkCoupon'
  ]) ?>
  <?= $this->Form->input('coupon_code', [
    'type' => 'text',
    'placeholder' => 'Apply Coupon Code',
    'label' => false
  ]) ?>
  <label class="hvr-sweep-to-right">
    <?= $this->Form->submit('Apply Coupon', ['id' => 'applyCoupon']) ?>
  </label>
  <label id="couponUpdate"></label>
  <label id="loading" style="display:none;">Loading...</label>
  <?php
     $data = $this->Html->script('#checkCoupon')->serializeForm(['isForm' => true, 'inline' => true]);
     $this->Html->script('#checkCoupon')->event(
       'submit',
       $this->Html->script(
        [
          'controller' => 'Coupons',
          'action' => 'ajax_checkCoupon'
        ],
        [
          'update' => '#couponUpdate',
          'data' => $data,
          'async' => true,
          'dataExpression' => true,
          'before' => "$('#loading').fadeIn();$('#applyCoupon').attr('disabled','disabled');",
          'complete' => "$('#loading').fadeOut();$('#applyCoupon').removeAttr('disabled');"
        ]
      )
    );
   ?>
  </div>

错误:在第 18 行的字符串上调用成员函数 serializeForm()checkout.ctp

4

0 回答 0