Welcome Guest, Not a member yet? Register   Sign In
CI best practice for outputting JSON content
#1

[eluser]Chillahan[/eluser]
I see sometimes folks just echo the data that's json_encoded, others set the content type, others set additional headers. So right now I am using the following (which could go into a helper function). Does this seem like the best practice, using CI libraries, etc. (vs. straight "header()" and "echo" statements)? Or is some of this superfluous/inefficient/possibly harmful?

Code:
$this->output->set_content_type('application/json');
$this->output->set_header('Cache-Control: no-cache, must-revalidate');
$this->output->set_header('Expires: '.date('r', time()+(86400*365)));

$output = json_encode(array(
    'key' => 'value',
    'key' => $value
));

$this->output->set_output($output);
#2

[eluser]fedeisas[/eluser]
Hi! I don't know if this is the best approach, but I have a json_view.php in my /views folder.

Code:
<?php
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
echo json_encode($output);

I use it a lot when doing AJAX requests, as this:

Code:
function foo($bar) {
   if($bar) {
      $output['status'] = "OK";
      $output['message'] = "There is bar!";
   } else {
      $output['status'] = "NOTOK";
      $output['message'] = "There isn't bar!";
   }
  
   $this->data['output'] = $output;
   $this->load->view('json_view',$this->data);
}
#3

[eluser]Chillahan[/eluser]
That's cool too. How come you use $this->data though, and not just a local array $data? Are you doing something modular or re-using the data somewhere? (just curious!)
#4

[eluser]fedeisas[/eluser]
[quote author="Chillahan" date="1306556442"]That's cool too. How come you use $this->data though, and not just a local array $data? Are you doing something modular or re-using the data somewhere? (just curious!)[/quote]

Nope, nothing fancy in there. I've just copy pasted some code, and that's why I've used $this->data. You can just pass a regular array to json_encode, and that's it. I use this json_view a lot when handling ajax request (form validations, populating dropdowns, etc.).




Theme © iAndrew 2016 - Forum software by © MyBB