在Yii中通过Ajax提交表单。 Yii是双重提交表格

时间:2016-03-14 21:17:48

标签: php jquery ajax yii2

我有以下内容:

我的观点

<?php $form = ActiveForm::begin(['id' => 'emailForm', 'action' => 'send-email', 'method' => 'post', 'enableAjaxValidation' => false, 'options' => ['class' => '']]) ?> 
<?= $form->field($emailModel, 'verifyCode')->widget(Captcha::className(), [
    'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
]) ?>
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'email-button']) ?>

我的控制器

  public function actionSendEmail() {
    Yii::$app->response->format = Response::FORMAT_JSON;
    $model = new EmailModel();
    if ($model->load(Yii::$app->request->post()) && $model->validate()) {
      return ['info' => "Your message has been sent!"];
    } else {
      // error
      // return $model->errors;
      return ActiveForm::validate($model);
    }

我的模特

 public function rules()
    {
        return [
            [['name', 'from', 'to', 'message'], 'required'],
            [['from', 'to'], 'email'],
            ['verifyCode', 'captcha'],
        ];

的javascript

jQuery(function() {
    $('#emailForm').submit(function(event) {
        event.preventDefault();
        $.post('send-email', $( "#emailForm" ).serialize(), function(data) {
            console.log (data);
//          $('#emailAlert').show().empty().append(data);
        });
        return false;
enter code here

event.preventDefault();return false;并未阻止Yii自己提交表单,因此它是双重提交。

'enableAjaxValidation' => true会导致Yii在每个&amp;之后验证表单。每个字段的每次更改,所以我将其设置为false。

控制台抛出:

XHR finished loading: POST "http://localhost:81/shopping/send-email".send @ jquery.js
  Object {info: "Your message has been sent!"}
XHR finished loading: POST "http://localhost:81/shopping/send-email".send @ jquery.js
  Object {info: "Your message has been sent!"}

1 个答案:

答案 0 :(得分:0)

@ck_arjun有解决方案。我不得不将JavaScript更改为

$('#emailForm').on('beforeSubmit', function(event) {

我不得不使用.on(),因为JQuery没有.beforeSubmit() http://api.jquery.com/category/events/form-events/