Yii: use ajax function via htmlOptions attribute

By: lars

If you want to trigger an ajax call on a Yii form element onchange, you can pass an array of ajax attributes as one of the “htmlOptions” like so:

<?php echo $form->textField($model,'my_input_field',array(
	'ajax' => array(
		'type'=>'POST', //request type
		'url'=>$this->createUrl('site/ajaxAction'), // url to call controller action
		'success'=>' function(data) { $(\'#my_output_field\').val(data) }',// function to call onsuccess 
             // "data" is returned data and function can be regular js or jQuery
             // here we are are updating the value of another field that has id "my_output_field"
)); ?>

and the (site) controller action would look something like:

public function actionAjaxAction() {
  [check/filter inputs...]
  [data functions...]
  echo $my_val_string;
Categories: Yii

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s