简体   繁体   中英

while using ajax to save data in yii 2.0 it save twice and null value in database

i am newbie in yii and php. i try to save data using ajax in yii framework but it save twice in database with null value. and after insert it redirect to other page and show {"success":"True"}. I want success message under the text field. Here is my code :(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()];
        }

    }

Model(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'),
        ];
    }
}

please give me a solution if any one know.

It's because you are using 'enableAjaxValidation'=>true and your action loads model's data on each POST query and save it.

If you save form via POST according to docs http://www.yiiframework.com/doc-2.0/guide-input-validation.html#ajax-validation you should add this construction:

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

我添加了'enableAjaxValidation'=> true,我的现在运行良好

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM