1

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.

2
  • remove $model->attributes=$request->post() you already did fill your safe attributes by doing $model->load($request->post()). then try to add print_r($request->post());die(); and see which output you get. Commented Mar 10, 2016 at 9:23
  • i get value success fully but the value are not save in database only null value store in database. can u give me solution...plzz Commented Mar 10, 2016 at 10:47

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

i appreciate you for your response but can u give me a sloution for saving null value in datatabse .
Also u can add behavior to format empty values on before save event.
0

I added 'enableAjaxValidation' => true and mine is now working well

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.