Reputation: 963
From within my scrip.js file, I'm using jquery $.post function to post some data (Actually as of right now I'm just trying get my call back to work so I can read some data).
$('document').ready(function(){
$.post("index.php/main/showData",
function(data){
console.log(data);
for (var name in data){
alert(name);
}
}, "json");
});
I'm using codeigniter to access to data the data from mysql:
class Main extends CI_Controller
{
function showData()
{
$this->load->model('ajax');
$array = array($this->ajax->getRecArray());
// $this->index();
echo json_encode($array);
}
My model
class Ajax extends CI_Model
{
function getRecArray()
{
$query = $this->db->query("SELECT * FROM record_table WHERE id = 1");
$row = $query->result();
return $row;
}
}
When I console.log(data) I get:
[[Object { id="1", name="scott"}]]
My question is, How do I access the individual properties or objects from with script.js? For example, how do I access the value of name in that Object array?
Upvotes: 0
Views: 114
Reputation: 16585
$('document').ready(function(){
$.post("index.php/main/showData",
function(data){
console.log(data);
for (var name in data[0][0]){
alert(data[0][0][name]);
}
}, "json");
});
That should do it.
When you iterate over an object using for .. in, the specified variable doesn't contain the data, but the string of the member name. In JS you can access object members by the syntax data.member, or data["member"], and you will want to use the later in this case since you have the string.
Additionally in this specific case the data is an object inside an array which is inside an array, here is the returned data broken down by levels:
[
[
Object {
id="1",
name="scott"
}
]
]
Hence why you need the syntax data[0][0][name]; this should be easy to fix in the PHP counter part.
Upvotes: 1