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?



30.7k

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?



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


30.7k

use

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



30.7k
edited Nov '16

to show code properly, have a look here: https://forum.phalconphp.com/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



1.3k
edited Nov '16

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



30.7k

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

        // ...
    }


1.3k
  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.



30.7k

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


1.3k

Exception: Response was already sent



1.3k

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.



1.3k
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



30.7k

Hi again,

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



1.3k

Thank you! wait...



30.7k

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