CakePHP 3:使用Ajax从数据库中检索数据

时间:2016-06-14 12:31:07

标签: ajax cakephp cakephp-3.0 cakephp-ajaxhelper

我正在开发一个具有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->value$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>

错误:在checkout.ctp

中第18行的字符串上调用成员函数serializeForm()

0 个答案:

没有答案
相关问题