使用ajax在yii 2.0中保存数据时,它在数据库中保存两次并保存null值

时间:2016-03-10 08:14:00

标签: php ajax yii yii2

我是yii和php的新手。我尝试在yii框架中使用ajax保存数据,但它在数据库中保存两次,值为null。插入后,它会重定向到其他页面并显示{“success”:“True”}。我希望在文本字段下成功留言。  这是我的代码:(index.php)

<div class="news_letter">
 <?php $form =ActiveForm::begin([
         'id'=>'newslatter',
         'method' => 'post',
         'action' => ['home/save'],
        //'action' => ['newslatter/Save'],
         'enableAjaxValidation'=>true,
       // 'validationUrl'=>['home/validate'],

 ]);?>


 <?php  $model= new Addnewslatter;?>

    <div class="container">
        <h1>Subscribe to the newsletter</h1>
        <span>We'll never bother you, we promise!</span>
       <!--   <input type="text" name="txt1" placeholder="Email..." class="email">-->
        <?=$form->field($model,'email')->textInput(['maxlength' => 255,'class' => 'email','placeholder'=>' Enter Email'])->label(false) ?>
        <?= Html::submitButton('submit', ['class' => 'submit']) ?>

</div>

<script>
$(document).ready(function() {

  $('body').on('beforeSubmit', '#newslatter', function () {
        var form = $(this);
         // return false if form still have some validation errors
         if (form.find('.has-error').length) {
              return false;
         }
         // submit form
         $.ajax({
              url: form.attr('action'),
              type: 'post',
              data: form.serialize(),
              success: function (response) {
                   // do something with response
              }
         });
         return false;
    });
});

  </script>

  <?php ActiveForm::end(); ?>
  </div>

COntroller:(HomeController.php)

  public function actionSave()
    {
        $model = new AddNewslatter();
        $request = \Yii::$app->getRequest();
        if ($request->isPost && $model->load($request->post())) {
            $model->attributes=$request->post();


            \Yii::$app->response->format = Response::FORMAT_JSON;
            //return ['success'=>'Response'];
            return ['success' =>$model->save()];
        }

    }

模型(Addnewslatter.php)

    <?php

namespace app\models;

use Yii;
use yii\base\Model;
use app\controllers\Addnewscontoller;

/**
 * This is the model class for table "newslatter".
 *
 * @property integer $id
 * @property string $email
 */
class Addnewslatter extends \yii\db\ActiveRecord
{

    public $email;

    public static function tableName()
    {
        return 'newslatter';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['email'], 'required'],
            ['email','email']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => \Yii::t('app', 'id'),
            'email' => \Yii::t('app', 'email'),
        ];
    }
}

如果有人知道,请给我一个解决方案。

2 个答案:

答案 0 :(得分:1)

这是因为您正在使用'enableAjaxValidation'=>true并且您的操作会在每个POST查询中加载模型的数据并保存。

如果您根据文档http://www.yiiframework.com/doc-2.0/guide-input-validation.html#ajax-validation通过POST保存表单,则应添加此结构:

if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
    Yii::$app->response->format = Response::FORMAT_JSON;
    return ActiveForm::validate($model);
}

答案 1 :(得分:0)

我添加了'enableAjaxValidation'=&gt;是的,我的现在运作良好