here is an old code of mine that i am using everywhere for ajax calls
<?php
namespace Whatever\api\Controllers;
use Phalcon\Mvc\Controller;
/**
* Class UsersController
*
* @package Api\Controller
*/
class BaseController extends Controller
{
protected $translationService;
public function onConstruct() {
$this->translationService = $this->getDI()->getShared("getTranslationMessages");
}
public function translate($name) {
return $this->translationService->query($name);
}
/**
* allows only ajax calls
*
* @param bool $onlyGet
* @param bool $token
* @param bool $soft
*/
public function onlyAjax($onlyGet = false, $token = false, $soft = false)
{
if ($this->request->isAjax() == false) {
return $this->handleAjaxError($soft);
}
if ($onlyGet === true) {
if ($this->request->isGet() === false) {
return $this->handleAjaxError($soft);
}
}
if ($token && $this->security->checkToken() == false) {
return $this->handleAjaxError($soft);
}
}
public function handleAjaxError($soft = false)
{
if ($soft === false) {
$this->response->setStatusCode(404, 'Not found');
$this->response->redirect("/404");
}
$this->response->setJsonContent(
array(
'success' => false,
'url' => $this->request->getURI(),
'parameters' => $this->dispatcher->getParams()
)
);
}
public function afterExecuteRoute(\Phalcon\Mvc\Dispatcher $dispatcher)
{
if ($this->request->isAjax() == true) {
$this->response->setContentType('application/json', 'UTF-8');
$data = $this->view->getParamsToView();
$json = [];
if (isset($data['error']) && $data['error'] !== 0 && $data['error'] !== true) {
$json['success'] = false;
$json['message'] = $data['error'];
} else {
$json['success'] = true;
if (isset($data['message'])) {
$json['message'] = $data['message'];
}
if (isset($data['results'])) {
$json['results'] = $data['results'];
}
}
$this->response->setJsonContent($json);
}
}
public function onlyLoggedUsers()
{
if ($this->getDI()->getShared("auth")->isUserSignedIn() === false) {
http_response_code(401); //unauthorized
echo json_encode(
[
'success' => false
]
);
exit;
}
}
}
and then for actually stuff
<?php
namespace Whatever\api\Controllers;
use Helpers\Uploads\HandleUpload;
class UploadsController extends BaseController {
public function AvatarAction(){
$this->onlyAjax();
$this->onlyLoggedUsers();
$this->view->error = 0;
$user_id = $this->auth->getUserId();
$uploadAdapter = new \whatever\Plugins\Uploads\Adapter\UserAvatar($user_id, [
"watermark" => false,
"trim" => true
]
);
$handleUpload = new HandleUpload($uploadAdapter);
$errors = $handleUpload->errors;
if (count($errors) > 0){
$this->view->error = $errors[0];
return false;
}
$result = [];
$result['success'] = true;
$this->view->results = $result;
return false;
}
}