Base on lexx-d answer, this is my baseController - For complex apps with mix of pure and Ajax calls. No need to change controller and action logic to return params!
Just send Ajax call and all decisions will be made:
use Phalcon\Mvc\Controller;
use Phalcon\Mvc\View;
class ControllerBase extends Controller
{
// After route executed event
public function afterExecuteRoute(\Phalcon\Mvc\Dispatcher $dispatcher) {
if($this->request->isAjax() == true) {
$this->view->disableLevel(array(
View::LEVEL_ACTION_VIEW => true,
View::LEVEL_LAYOUT => true,
View::LEVEL_MAIN_LAYOUT => true,
View::LEVEL_AFTER_TEMPLATE => true,
View::LEVEL_BEFORE_TEMPLATE => true
));
$this->response->setContentType('application/json', 'UTF-8');
$data = $this->view->getParamsToView();
/*
* Or for returnish action lovers:
* -> $data = $dispatcher->getReturnedValue();
*/
/* Set global params if is not set in controller/action */
if (is_array($data)) {
$data['success'] = isset($data['success']) ?: true;
$data['message'] = isset($data['message']) ?: '';
$data = json_encode($data);
}
$this->response->setContent($data);
}
return $this->response->send();
}
}
Then this is controller Use case: PostsController
class PostsController extends ControllerBase
{
public function showAction()
{
$posts = Post::findAll();
$this->view->posts = $posts;
}
}
Ajax call and return json value:
$.ajax(
{
url:"/posts/show/",
success: function (result){
console.log(result); /* Result: {success: true, message: '', posts: [{...}{...}{...}...}] */
}
}
);