CodeIgniter Forums
error when call JSON response - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: error when call JSON response (/showthread.php?tid=77516)



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" ...
   
____
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.


RE: error when call JSON response - davodm - 01-31-2021

I have the same problem on ResponseTrait.php at line 398.
The problem is about calling setContentType in Response Class.
So I suggest defining $this->response first in the "respond()" function.

PHP Code:
public function respond($data nullint $status nullstring $message '')
{
$this->response=service('response'); 



RE: error when call JSON response - hasanbasri93 - 12-18-2022

(01-31-2021, 01:35 AM)davodm Wrote: I have the same problem on ResponseTrait.php at line 398.
The problem is about calling setContentType in Response Class.
So I suggest defining $this->response first in the "respond()" function.

PHP Code:
public function respond($data nullint $status nullstring $message '')
{
$this->response=service('response'); 

This work for me