I have a PHP script that makes query to DB and returns the result as JSON data. This file contains some Codeigniter specific functions.
This functions recieve id and returns back to the JS code some data from a table.
public function get_l($id){
//$id is not empty variable
$this->db->where('id',$id);
$q=$this->db->get('news');
$res = $q->result_array();
$this->output->set_header("HTTP/1.0 200 OK");
$this->output->set_header("HTTP/1.1 200 OK");
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate");
$this->output->set_header("Cache-Control: post-check=0, pre-check=0");
$this->output->set_header("Content-Type: application/json; charset=utf-8");
$this->output->set_header("Pragma: no-cache");
$out = json_encode($res);
$this->output->set_output($out);
}
And then I need to process that JSON with the next JS code:
function getContent(id){
$.post('/admin_ajax/news/get',
{
id: id
},
function(result)
{
alert(result+"\n"+result.length);//this will output [object Object] 1
for (var key in result)
{
alert(key+':'+result[key]); //and this 0:[object Object]
}
alert(result.title); //here we are getting undefined
},
'json'
);
I am not receiving errors or warnings in console. And in the firebug I see what was returned from the server.
HTTP headers:
Server nginx/1.1.19
Date Fri, 26 Oct 2012 11:59:12 GMT
Content-Type application/json; charset=utf-8
Content-Length 85
Connection keep-alive
X-Powered-By PHP/5.3.10-1ubuntu3.4
Cache-Control post-check=0, pre-check=0
Pragma no-cache
And response:
[{"id":"5","title":"test","alias":"test","content":"tes","date":"123","type":"test"}]
JSON:
alias "test"
content "tes"
date "123"
id "5"
title "test"
type "test"
I found a similar question here but it wasn't helpful.