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

Response setJsonContent

Good day! When I use $this->response->setJsonContent([1 => ...]) inside the Action all appears well. But if it's built inside afterExecuteRoute then becomes the contentType to "application/json", and data of the array are not displayed. What could be the problem?



43.9k

Hi,

What's your code in afterExecuteRoute ?

Hey, I handle my rest API in a similar way. I have BaseController which other controllers extend. In the BaseController I have the following:

// Return the API response.
public function afterExecuteRoute()
{
    // Status code & Response header
    $this->response->setStatusCode($this->_response['statusCode'], $this->_statusCodes[$this->_response['statusCode']]);
    $this->response->setHeader('Access-Control-Allow-Origin', '*');

    // Allow user to choose content type. Defaults to JSON
    if ($this->request->getHeader('Accept') == 'application/xml') {
        $this->response->setContentType('application/xml', 'UTF-8');

        // @TODO: generate XML from array
        d($this->_response);
    } else {
        $this->response->setContentType('application/json', 'UTF-8');
        return $this->response->setJsonContent($this->_response)->send();
    }
}

So in every controller I just pass data to $this->_response and afterExecuteRoute in my BaseController does the rest.

It has to work for you too, but as @le51 asked what is your actual code?



5.8k
edited Nov '16
    public function afterExecuteRoute(Dispatcher $dispatcher)
    {
        $this->response->setJsonContent(array(
            'http_status' => 200,
            'response' => [
                'status' => true,
                'error_code' => 0,
                'data' => [
                    'message' => 'Удачный тест!'
                ]
            ]
        ), JSON_UNESCAPED_UNICODE);
        return $this->response;
    }


43.9k

use

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



43.9k
edited Nov '16

to show code properly, have a look here: https://forum.phalcon.io/help/markdown

section "code block". Insert a blank line before and after the three opening backticks and a blank line before the three closing ones



5.8k
edited Nov '16

if $this->response->send() then "Exception: Response was already sent". I have a full MVC use.



43.9k

ok, so if you want to send only json response in a mvc application context, you have to set the view render level to no render:


    public function findAction()
    {
        // This is an Ajax response so it doesn't generate any kind of view
        $this->view->setRenderLevel(
            View::LEVEL_NO_RENDER
        );

        // ...
    }


5.8k
  namespace Project\Controllers;
  use Phalcon\Http\Response;
  use Phalcon\Mvc\Dispatcher;
  use Phalcon\Mvc\View;

  class ApitestController extends ControllerBase
  {
      public function initialize()
      {
          $this->view->setRenderLevel(
              View::LEVEL_NO_RENDER
          );

      }

      public function afterExecuteRoute(Dispatcher $dispatcher)
      {
          return $this->response->setJsonContent(array(
              'http_status' => 200,
              'response' => [
                  'status' => true,
                  'error_code' => 0,
                  'data' => [
                      'message' => 'Удачный тест!'
                  ]
              ]
          ), JSON_UNESCAPED_UNICODE);
      }

And returns ContentType: applicatoin/json, but the output is empty.



43.9k

now, normally, this should work:


return $this->response->setJsonContent(array(
              'http_status' => 200,
              'response' => [
                  'status' => true,
                  'error_code' => 0,
                  'data' => [
                      'message' => 'Удачный тест!'
                  ]
              ]
          ), JSON_UNESCAPED_UNICODE)->send();


5.8k

Exception: Response was already sent



5.8k

Zephyr in the source code there is a check If this._content != null then display this._content. But for some reason it does not work, although response->getContent() output the array in JSON format.



5.8k
edited Nov '16

so

<?php
    $dependencyInjector->set('dispatcher',
    function()
    {
    $dispatcher = new Dispatcher();
    $dispatcher->setDefaultNamespace('Project\Controllers');

    return $dispatcher;
    }, true
    );

p.s. not able to adequately display the code



43.9k

Hi again,

this looks strange, I will make some further investigation on my own. I'll keep you in touch ...



5.8k

Thank you! wait...



43.9k

Hi,

try with that, it's working for me.


<?php

class ApiController extends ControllerBase
{

    protected $response;

    public function initialize()
    {
        $this->view->disable();
    }

    public function afterExecuteRoute()
    {
        $this->response->setJsonContent($this->content, JSON_NUMERIC_CHECK);
        $this->response->send();
    }

    public function testAction()
    {
        $this->response = MyModel::find();
    }