My index post controller list all posts in the following way
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'template'=>"{items}\n{pager}",
)); ?>
My view _view has the ajax-link
<div id="comments"></div>
<?php echo CHtml::ajaxLink('List Comments', array('listComments'),
array('update' => '#comments'))?>
listComments is a function in my PostController
public function actionListComments()
{
$this->renderPartial('_comments',array(
'post'=>$model,
'comments'=>$model->comments,
));
}
When I click to the ajax link , nothing happens,
it points to localhost/blog/#
Can you help me please ?
The problem is actionListComments() method returns non-200 HTTP code because of undefined $model variable in it. Try something like this:
_view:
<div id="comments"></div>
<?php echo CHtml::ajaxLink('List Comments', array('listComments', 'id' => $data->id),
array('update' => '#comments'))?>
PostController:
public function actionListComments($id)
{
$model = Posts::model()->findByPk($id);
if($model !== null)
$this->renderPartial('_comments',array(
'post'=>$model,
'comments'=>$model->comments,
));
else
Yii::log('Unknown post with $id ' . $id, 'error');
}
First in actionListComments()
you have a variable $model
which you haven't instantiated.
Assuming you are getting the $model->id
from the link it should change to:
<?php echo CHtml::ajaxLink('List Comments', array('listComments','id'=>$data->id),
array('update' => '#comments'))?>
Next, your actionListComments()
should access the id
, use this to load a model and its comments, and send this to the required view
public function actionListComments($id){
$model=$this->loadModel($id);
$this->renderPartial('_comments',array('model'=>$model));
}
There is no need to send $model->comments
as we are already sending $model
therefore we can access $model->comments
.
many things could go wrong about that. As ajax calls cant be debugged with normal compnonents like
CVarDumper::Dump();
die();
Above code will not show you anything in the browser area. The best way to debug ajax calls is using inspectElement. Click on Network
. Now when you click on ajaxLink it will show you whether the ajax request was sent successfully. It will be red if the request was unsuccessful. When you click on the request made. It will show you 3 tabs on right named Header
, Preview
, Response
. As you want to render the page so the content-Type should be text/html
.
As far as your code is concerned clearly you are using $model without instantiating it so it is returning error.
Read the error returned in your case.