Update content in AJAX with renderPartial

The easiest way to update content in AJAX is to use the renderPartial method.

For this exemple I have three files: a controller (HelloWorldController.php) and two views (index.php and _ajaxContent.php)


controllers/HelloWorldController.php
class HelloWorldController extends CController
{
	public function actionIndex()
	{
		$data = array();
		$data["myValue"] = "Content loaded";
		
		$this->render('index', $data);
	}
	
	public function actionUpdateAjax()
	{
		$data = array();
		$data["myValue"] = "Content updated in AJAX";
		
		$this->renderPartial('_ajaxContent', $data, false, true);
	}
}

The actionIndex set myValue to "Content loaded" and this variable is passed to the view "index.php" and to "_ajaxContent.php"


Note: if using accessRules() in your controller file, you will need to modify accessRules() by adding the appropriate part of the function name to a rule set - in this case 'updateajax' like this:

array('allow',  // allow all users to perform 'index' and 'view' actions
	'actions'=>array('index','view','updateajax'),
	'users'=>array('*'),
		),
views/helloWorld/index.php
<div id="data">
   <?php $this->renderPartial('_ajaxContent', array('myValue'=>$myValue)); ?>
</div>

<?php echo CHtml::ajaxButton ("Update data",
                              CController::createUrl('helloWorld/UpdateAjax'), 
                              array('update' => '#data'));
?>

The ajaxButton call "actionUpdateAjax" and the returned data are inserted in the div "data"


views/helloWorld/_ajaxContent.php
<?php echo $myValue ?>

Display $myValue


Now, run index.php?r=helloWorld

Enjoy!

Links
43 0
46 followers
Viewed: 361 140 times
Version: 1.1
Category: Tutorials
Tags: AJAX
Written by: Burzum
Last updated by: hairylunch
Created on: Sep 30, 2009
Last updated: 12 years ago
Update Article

Revisions

View all history

Related Articles