We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Routing, Ajax calls wrong function!

Hello!

I have a controller: TestController View: indexAction (show site) method: retriveAction (gets statuses to show via ajax call)

When I use URL "/sofiety/test" Ajax works fine. It calls retrive and gets the information.

When I call "/sofiety/test/index" it fails. Exact same call as original... It calls the original view (index) again instead of retrieve.

I can't use Ajax in any action, like "showAction". Only on default controller call. It just calls the original view/

My routing is standard:


<?php
/*
 * Define custom routes. File gets included in the router service definition.
 */
$router = new Phalcon\Mvc\Router();

$router->add('/confirm/{code}/{email}', array(
        'controller' => 'session',
        'action' => 'confirmEmail'
));

return $router;

Thank you! :)



11.6k

Sort your ajax/non ajax in your controllerBase.php: then, no need to specify parameters you pass with ajax in the route definition.

also set $this->view->disable(); in the controller action

routes.php:


        $router->add("/users/myAjaxFunc", array(
            'controller' => 'users',
            'action' => 'myAjaxFunc',
        ));

controllerBase example:


    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
            ));

          $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']) ?: 'anything_message';
                $data = json_encode($data);
            }
            $this->response->setContent($data);

        }

        return $this->response->send();
    }

the datas sent back by the controller will be in response.responseText

            /* 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']) ?: 'anything_message';
                $data = json_encode($data);
            }
            $this->response->setContent($data);

Just use `$this->response->setJsonContent($data) instead of json_encode etc. This whole if is not needed.