CodeIgniter Forums
error when call JSON response - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forum-28.html)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forum-30.html)
+--- Thread: error when call JSON response (/thread-77516.html)



error when call JSON response - mylastof - 09-10-2020

Hello, I don't know this is bug or not. But ...

I have Controller A with method like :

Code:
public function myjson() {
     ....
     ....

     return $this->respond($json); // output JSON    
}

when call : http://localhost:8080/a/myjson
showing the output, JSON

but the problem is, when call by other controller show Error like
"Call to a member function setContentType() on null" ...
[attachment=1861]
____
when code changed to

Code:
public function myjson() {
     ....
     ....

     return json_encode($json); // output JSON    
}

no error


RE: error when call JSON response - T.O.M. - 09-10-2020

If you want to return JSON from your controller method you should set JSON to response and return it - https://codeigniter.com/user_guide/outgoing/response.html?highlight=setjson#setting-the-output

PHP Code:
return $this->response->setJSON($json); 

Besides, variable $json may be an array (or maybe, it should be) - it is converted automatically to JSON.