<div class="form-group">
<div class="col-sm-12 text-right">
<?=
CHtml::ajaxSubmitButton( Yii::t( 'zr', 'Add' ), [ 'createProperty' ],
[
'type' => 'POST',
'dataType' => 'json',
'data' => 'js:$("#property-form").serialize()',
'complete' => 'js:function(){location.reload();}',
'success' => 'js:function(resp){console.log(resp);}',
],
[ 'class' => 'btn btn-default' ] );
?>
</div>
</div>
Serialize form with $(form#form-id).serialize()
method.
Reload whole page with location.reload()
method.
To accept response in JSON
format, set dataType
to json
. Then we can use response as JSON
object (no need to parse response with $.parseJSON()
).
Action createProperty
may look like as following:
<?php
public function actionCreateProperty()
{
//echo CJSON::encode( $_POST[ 'Property' ] ); // just echo data back
// actual data saving:
$model = new Property();
if ( isset( $_POST[ 'Property' ] ) )
{
$model->attributes = $_POST[ 'Property' ];
if ( $model->save() )
CJSON::encode( [ 'msg' => Yii::t( 'zr', 'New Property successfully added.' ) ] );
else
CJSON::encode( $model->getErrors() );
}
}
We can also control request type via filters, for example, we can accept only AJAX POST
request:
<?php
public function filters()
{
return [
'accessControl',
'postOnly + createProperty',
'ajaxOnly + createProperty',
];
}