Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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.



7.9k

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



53.2k
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;
    }
}