Happy new year guys!
I'm trying to wire up a small phalcon project from scratch, but I am having trouble displaying a view. I am able to call the controller action using an ajax request from my js file
$('#create_user').click(function () {
$.ajax({
url: "/user/create",
dataType: "json",
success: function (resp) {
console.log('successfully getting create page: ' + resp);
},
error: function (x, status, error) {
console.log(x.responseText);
console.log(error);
},
complete: function () {
}
});
});
which I confirmed by setting a breakpoint in the action.
<?php
use Phalcon\Mvc\Controller;
class UserController extends Controller
{
public function indexAction()
{
}
public function createAction()
{
$this->assets
->addJs('js/jquery.js')
->addJs('js/user.js');
$this->view->pick('/users/create');
}
}
However, the view doesn't seem to get picked, and the html text of the current view is returned to the error function of the ajax request. I don't konw what i'm doing wrong, please help
The right way of doing that should be using the phalcon mvc structure.
Your project directory should look like this(basic example):
-app
-controllers
-models
-views
-public
If you respect this structure you actually don't need to pick your views like this $this->view->pick('/users/create');
You only have to set the path of your views directory into the view service
$di->setShared('view', function () use ($config, $di) {
$view = new View();
$view->setViewsDir("path/to/your/views");
$view->setLayoutsDir("path/to/your/layuts");
$view->registerEngines(array(
'.volt' => function ($view, $di) use ($config) {
$volt = new VoltEngine($view, $di);
$volt->setOptions(array(
'stat' => true,
'compileAlways' => true
));
return $volt;
},
'.phtml' => 'Phalcon\Mvc\View\Engine\Php'
));
return $view;
});
If you want to receive a json response you have to send one first, so your controller should look like this
use Phalcon\Mvc\Controller;
class UserController extends Controller
{
public function indexAction()
{
}
public function createAction()
{
$this->assets
->addJs('js/jquery.js')
->addJs('js/user.js');
$this->response->setJsonContent(["data" => ["Your data"]]);
$this->response->send();
}
}
And your js function should now receive a json response with a data object in it