I have a project where I want to return two different outputs based on if it is AJAX or not.
When I query GET /controller/action I want it to display a view (x) that extends view (y) as HTML. When I query the same action with AJAX, I want it to display only the contents og view x in a JSON-object.
Example: view x:
{% extends "y.volt" %}
{% block footer %}
<h1>Test</h1>
{% endblock %}
If it is an AJAX request, I want to output the following:
echo json_encode(array('some' => 'data', 'contents' => '<h1>Test</h1>'));
I have started out with the following in my Base Controller:
public function afterExecuteRoute(\Phalcon\Mvc\Dispatcher $dispatcher) {
if ($this->request->isAjax()) {
$this->config->is_ajax = true;
$this->view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_ACTION_VIEW);
}
}
But what event do I have to make to catch the rendered view, and transform it into a json-object? This is what I want, but what events and which functions do I have to use?
public function afterRenderedView() {
if($this->config->is_ajax) {
$this->response->setContentType('application/json', 'UTF-8');
$this->response->setContent(json_encode(array('some' => 'data', 'contents' => $this->view->getContents())));
return false;
}
}