在Yii中使用AJAX验证表单

时间:2017-10-19 14:30:48

标签: php ajax yii

我是Yii框架的新手,我有一个创建新用户的工作表单, 当前表单重定向到一个视图页面,其中有一个输入用户的视图,我希望在显示成功消息后保持在同一页面。我想用AJAX制作它。

这是我的观点:

<?php
/* @var $this UserController */
/* @var $model User */

$this->breadcrumbs=array(
    'Users'=>array('index'),
    'Create',
);

$this->menu=array(
    array('label'=>'List User', 'url'=>array('index')),
    array('label'=>'Manage User', 'url'=>array('admin')),
);
?>
<h1>Create User</h1>
<?php $this->renderPartial('_form', array('model'=>$model)); ?>

这是我的控制器:

class UserController extends Controller
{
...

    public function actionCreate()
    {
        $model=new User;

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if(isset($_POST['User']))
        {
            $model->attributes=$_POST['User'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }


        $this->render('create',array(
            'model'=>$model,
        ));

    }

...
/**
     * Performs the AJAX validation.
     * @param User $model the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }


...
}

1 个答案:

答案 0 :(得分:0)

在你的表格中写下:

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'user-form',
    // Please note: When you enable ajax validation, make sure the corresponding
    // controller action is handling ajax validation correctly.
    // There is a call to performAjaxValidation() commented in generated controller code.
    // See class documentation of CActiveForm for details on this.
    /*updated by Ismail*/
    'enableAjaxValidation'=>true,
    'clientOptions'=>array(
        'validateOnSubmit'=>true,
        'afterValidate' => 'js:function(form, data, hasError) {
            if(hasError) {
                return false;
            }
            else
            {
            // return true;  it will submit default way
                   ajaxSubmitHappen(form, data, hasError); //and it will submit by ajax function
               }
           }',
        'htmlOptions'=>array('role'=>"form")
))); ?>

然后是Javascript代码:

   <script>
        function  ajaxSubmitHappen(form, data, hasError) {
            if (!hasError) {
                $.ajax({
                    "type": "POST",
                    "url": "<?php echo $url;  ?>",
                    "data": form.serialize(),
                    "success": function (data) {
                        $('#successMessage').html('<div class="alert alert-success"><strong>Success!</strong> User added successfully. </div>');
                        setTimeout('$("#successMessage").fadeOut("slow")', 2000);
                    }
                });
                /*reset form after submitting*/
                $("#user-form")[0].reset();
            }
            else {
                $('#successMessage').html('<div class="alert alert-danger"><strong>Error!</strong> An error has occured, please try again. </div>');
                setTimeout('$("#successMessage").fadeOut("slow")', 2000);
            }
        }
    </script>