Iam trying to return json data from codeigniter view. but my code is not working.i have tried all options given in this site. but i could not able to return json data from view
this is controller code.
<?php
class Json extends CI_Controller
{
function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->model('get_json');
$data['message']=$this->get_json->get_fruits();
if ($data!== false)
{
$this->load->view('json',json_encode($data['message']));
}
}
}
my model
<?php
class get_json extends CI_Model
{
function __construct()
{
parent::__construct();
}
function get_fruits()
{
$sql = "SELECT * FROM fruit where name='Apple'";
$query = $this->db->query($sql);
// Fetch the result array from the result object and return it
return $query->result();
}
}
View code:
<?php
$this->output->set_content_type('application/json');
echo $message;
Please help me wwhere my code went wrong.
This is what iam getting in my logs:
ERROR - 2012-05-11 15:28:40 --> Severity: Notice --> Undefined variable: message C:\xampp\htdocs\ci\system\core\Loader.php(829) : eval()'d code 3
DEBUG - 2012-05-11 15:28:40 --> File loaded: application/views/json.php
Change your controller
indexmethod to this:And you should be good to go: you need to pass the array to
$this->load->view, not the encoded value.EDIT: as a side note, for this sort of thing you don’t even NEED a view. You can return the result directly from the controller:
Cleaner, puts everything in one place, and slightly more efficient.