Welcome Guest, Not a member yet? Register   Sign In
JSON formatting in the browser (missing headers)?
#1

I'm responding from an API using this:

Code:
return $this->setResponseFormat('json')->respond(json_encode($response), 200);

Now, I would 'expect' the proper headers would be set 'automagically' by doing this ... but NOTHING but the data is sent to the browser (no headers for some reason).

What is the 'hack' I need to use to make CI4 send the proper headers without me having to muck around with it?

This is extending the RerourceController ... if that matters.
Reply
#2

https://codeigniter.com/user_guide/outgo...-reference
PHP Code:
return $this->setResponseFormat('json')->respond(['error' => false]); 
respond($data[, $statusCode=200[, $message='']])
Parameters:
$data (mixed) – The data to return to the client. Either string or array.
$statusCode (int) – The HTTP status code to return. Defaults to 200
$message (string) – A custom “reason” message to return.
Reply
#3

Thanks, but that's just what I already did. This does NOT send a header of type json to the client. I had to do this for that to work: return $this->response->setJSON($this->model->find($id));

Now, to me that is a completely different way to do things ... and again; the docs are confusing.
Reply
#4

PHP Code:
return $this->setResponseFormat('json')->respond(['error' => false]); 
// equal
return $this->response->setJSON(['error' => false]);  

PHP Code:
// setResponseFormat($format) 
$this->format strtolower($format);

// respond($data) 
// $output contains json if $data not a string
if ($this->format === 'json')
{
    return $this->response->setJSON($output)->setStatusCode($status$message);


example code with browser output (pic, CI4.1 php 7.3) https://yadi.sk/i/VBFIGIaF-TLF2g

You can actually use setJSON() if you're comfortable.
I'm just showing that the example from the documentation works.

And by the way, when you passed the JSON string in the first example, the header was setted to text/html
link to code
Reply




Theme © iAndrew 2016 - Forum software by © MyBB