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 ?
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:
OR
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.