Noob Question- Display View In <Div> Via Ajax

Hi everyone,

I’m new to Yii, and have been given the task of making some enhancements to an existing Yii application.

I’ve racked my brain with this, I’m hoping someone can give me a push in the right direction.

What I am trying to do is this:

There is an existing controller called Reporting, with an action getReports. It is access via /reporting/getReports. It all functions perfectly.

The getReports methods does


$this->render('list', array('reportTypes' => $reportTypes));

, so it outputs everything to a view called ‘Reporting/list’. Just to clarify, the Reporting controller has no model…it uses other models to build the output.

I have been asked to make some changes so this report listing can be loaded on any page via a link on all pages. i.e. you click a link, it does an Ajax call then loads the contents into a div on the page.

I’ve edited the main.php view file an put a link there to call /reporting/getReports. This is where I am confused.

How do I get the view and display it in a div, given it isn’t in a JSON fomat? Is it as simple as doing an ajax call to Reporting/list and dumping the result in the Div? Or do I need to change he getReports method to renderPartial instead? Should renderPartial put the result into a different view file?

I’m sure this is an easy one. I’ve wasted a lot of time trying to get this work.

Thanks.

You could do the latter, but you can also output the renderpartial from the controller method by using echo.


echo $this->render('list', array('reportTypes' => $reportTypes), true);

Yii::app()->end();

So the Ajax call calls this new controller action that returns the content of the view and Ajax places it in a div. The new controller action function will probably be a copy of the existing function till the render (or you change the original function this way when you don’t need the original functionality anymore).

Thanks for the reply. I actually got it working by doing this in the main.php


                          if (isset($reportTypes)) 

                                $this->renderPartial('//reporting/getReports', array('reportTypes' => $reportTypes));


...

                                echo CHtml::ajaxLink('Rports', array('/reporting/getReports'), array('update' => '#panel-report'));




And in the reporting controller changed it to render partial:


$this->renderPartial('list', array('reportTypes' => $reportTypes));

Is there any benefit to do it your way instead?

Not that I can think of.