CActiveForm and ajaxSubmitButton not working

2019-07-23 03:47发布

This is my code in view:

    <?php
    $form = $this->beginWidget('CActiveForm', array(
        'id' => 'swim-subscribe-form',
        'enableAjaxValidation' => true,
        'action'=>"/mycontroller/myfunction"
            ));
    ?>
    <?php 
          echo CHtml::ajaxSubmitButton('Save',array('/mycontroller/myfunction'),array(
         'type'=>'POST',
         'dataType'=>'post',
         'success'=>'js:function(data){
          }',
          ));
     $this->endWidget();
     ?>

This is my controller:

public actionMyFunction(){
        $model = new MyModel;
        $this->performAjaxValidation($model);
        if ($model->save()) {
          $this->redirect('/another_controller');
        }
}
protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'swim-subscriber-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

This code somehow, it always do a submit my url /mycontroller/myfunction. It doesn't show on my console that I call the /mycontroller/myfunction through ajax. Why ?

UPDATE This is what generated my ajaxSubmitButton:

<input name="yt0" value="Save" id="yt0" type="submit">

Is this ok ?

标签: php yii
1条回答
兄弟一词,经得起流年.
2楼-- · 2019-07-23 04:03

You have a typo in your code. In the view file the ID of the form is
'id' => 'swim-subscribe-form',

But during ajax validation you are checking for the id
$_POST['ajax'] === 'swim-subscriber-form' // there is an extra R at the end of "subscriber"

Therefore the ajax validation never runs, the yii app never ends, and it is always considered as a submit.

Either fix your form ID-s, or remove the ID check from the ajax validation in the controller:

if (isset($_POST['ajax']) && $_POST['ajax'] === 'swim-subscribe-form') { // this has to match with the form ID
    echo CActiveForm::validate($model);
    Yii::app()->end();
}

OR

if(Yii::app()->getRequest()->getIsAjaxRequest()) {
    echo CActiveForm::validate($model);
    Yii::app()->end();
}

The form ID check is useful if you have multiple forms on a page (with same action), and you don't want to ajax validate each of them or if the ajax validation interferes with other ajax request to the same action. I rarely check for the form ID during ajax validation.

查看更多
登录 后发表回答