Simple Yii ajaxLink

This is just a simple tutorial for creating an ajaxLink in Yii. Since I looked all around and there wasn’t anything this straightforward, I thought I’d write it up myself. Feel free to add any comments or suggestions. My goal is to create a link that passes data through POST to one of my controller actions using the Yii AJAX interface. While researching how to do this the “Yii” way, I found no less than 5 different examples, none of which worked, and none of which purported to do exactly what I was looking to do. If you’re just looking for the simple example, here it is. In view that contains the link:

echo CHtml::ajaxLink(
  "Link Text",
  Yii::app()->createUrl( 'myController/ajaxRequest' ),
  array( // ajaxOptions
    'type' =>; 'POST',
    'beforeSend' => "function( request )
                       // Set up any pre-sending stuff like initializing progress indicators
    'success' => "function( data )
                    // handle return data
                    alert( data );
    'data' => array( 'val1' => '1', 'val2' => '2' )
  array( //htmlOptions
    'href' => Yii::app()->createUrl( 'myController/ajaxRequest' ),
    'class' => $class

Make sure to allow the user access to the particular action you’re calling through your AJAX request.

In the MyController.php file:

public function accessRules()
  return array(
    // ...
    array('deny',  // deny all users
Now let’s handle that request shall we?
Further along in MyController.php:
public function actionAjaxRequest()
  $val1 = $_POST['val1'];
  $val2 = $_POST['val2'];
  // Perform processing
  // echo the AJAX response
  echo "some sort of response";
  • yii/simple_yii_ajaxlink.txt
  • Последнее изменение: 2012/06/03 09:43
  • (внешнее изменение)