In: Programming|Yii
12 May 2010This 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('allow', 'actions'=>array('ajaxrequest'), 'users'=>array('@'), ), // ... array('deny', // deny all users 'users'=>array('*'), ), ); }
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::app()->end(); }
No related posts.
My name's Bryan Marble. I'm the founder of 5or7 Software, a bootstrapped software company in beautiful Manchester, NH.
I'm a former developer at HubSpot and I love talking startups, web usability and web apps in general and I'm always looking for new people to geek out with.
I'm currently developing GroupTrip, a group travel planning site that helps friends coordinate travel research and track expenses so that they can focus on the experience of the trip and not the logistics of traveling in groups. Check out the site, sign up for the e-mail list, and let me know if you have any feedback!