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

Phalcon Response

Hello,

I've got following code in my Controller:

private function checkUpdate($data){
    $this->view->disable();

    $this->response->setJsonContent($data);

    return $this->response;
}

Where $data is array.

And following AJAX call:

$("#checkUpdate").on('click', function() {
        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: '/update/data/<?php echo $entry->id; ?>/check',
            success: function(response){
                $("#updated").show();
                console.log(response);
            }
        });

If I'm not wrong it should work correctly however I've got empty response. When I tried to print $data in controller I've see correct array but it's not send.



11.0k

can you access data via post action ?

With:

private function checkUpdate($data){
    $this->view->disable();
    print_r($data)
}

I can see data by post with this no:

private function checkUpdate($data){
    $this->view->disable();

    $this->response->setJsonContent($data);

    return $this->response;
}

Try it with sending the response. because it's a private function not an action!

private function checkUpdate($data){
    $this->view->disable();

    $this->response->setJsonContent($data);

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

Even like that it is not working



125.8k
Accepted
answer

This is one instance where there isn't really much advantage to using framework code. I just use raw PHP:

protected function outputJSON($what_to_output){
    $this->view->disable();
    header('Content-type: text/json');
    echo json_encode($what_to_output);
    exit();
}

I'm using this base class for ajax responses:

class ControllerBase extends \Phalcon\Mvc\Controller
    protected $_forceAjaxResponse = false;
    public function afterExecuteRoute(Dispatcher $dispatcher)
    {
        if ($this->request->isAjax() || $this->_forceAjaxResponse) {
            $this->view->disable();
            $data = $this->view->getParamsToView();
            $this->response
                ->setContentType('application/json', 'utf-8')
                ->setContent(json_encode($data));
        }
        return $this->response->send();
    }
class SomeController extends ControllerBase
{
    public function someAction() {
        $this->view->data = ['your_data'=>'here'];
        $this->_forceAjaxResponse = true;
    }
}