Using Partial Views in the ExpressionEngine Control Panel (for ajax requests or similar)
If you want to use ajax to populate certain parts of your Control Panel user interface in ExpressionEngine, you will find that you have a problem if you want to use the standard MVC framework included, because EE will wrap all your views with the control panel “frame” (html/images/css etc).
For example, the following view is intended to be returned as a partial view to be called using ajax, but it will instead be wrapped by the EE control panel
public function ajax_example()
{
// --------------------------------------
// Load view and return it
// --------------------------------------
$data = array('some_view_data' => 'Value');
return $this->EE->load->view('ajax_example_view', $data, TRUE);
}
To fix this, all we have to do is grab the output from our view and spit it straight out to the browser without returning it to the calling function (which is where the frame is added).
public function ajax_example()
{
// --------------------------------------
// Load view and echo it
// --------------------------------------
$data = array('some_view_data' => 'Value');
echo $this->EE->load->view('ajax_example_view', $data, TRUE);
exit;
}
This works, but you do lose some functionality, such as seeing the output profiler and/or template debugger. However, we can fix this by using the EE/CI output class instead to display the view.
public function ajax_example()
{
// --------------------------------------
// Load view and display it
// --------------------------------------
$data = array('some_view_data' => 'Value');
$response = $this->EE->load->view('ajax_example_view', $data, TRUE);
$this->EE->output->set_output($response);
$this->EE->output->_display();
exit;
}
This works better, but we don’t always want to see the output profiler, especially on ajax requests because the profiler output could break the layout or, if we are returning JSON for example, can destroy the output totally. So, let’s wrap this up into a helper method with some optional parameters
public function ajax_example()
{
// --------------------------------------
// Load view and display it
// --------------------------------------
$data = array('some_view_data' => 'Value');
$this->partial_view('ajax_example_view', $data);
}
private function partial_view($view_name, $data, $show_profiler = null) {
$response = $this->EE->load->view($view_name, $data, TRUE);
if(isset($show_profiler)) {
$this->EE->output->enable_profiler($show_profiler);
}
$this->EE->output->set_output($response);
this->EE->output->_display();
exit;
}
