Skip to content

Instantly share code, notes, and snippets.

@b3457m0d3
Forked from umidjons/chtml-ajaxsubmitbutton.md
Last active August 29, 2015 14:17
Show Gist options
  • Save b3457m0d3/2159554c4b6f0d0df96b to your computer and use it in GitHub Desktop.
Save b3457m0d3/2159554c4b6f0d0df96b to your computer and use it in GitHub Desktop.

Using CHtml::ajaxSubmitButton in active forms

<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',
	];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment