Welcome Guest, Not a member yet? Register   Sign In
error when call JSON response
#1

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
Reply
#2

(This post was last modified: 09-10-2020, 11:18 PM by T.O.M..)

If you want to return JSON from your controller method you should set JSON to response and return it - https://codeigniter.com/user_guide/outgo...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.
Reply
#3

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'); 
Reply
#4

(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
Reply




Theme © iAndrew 2016 - Forum software by © MyBB