0

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?

1 Answer 1

1
 $('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.

Sign up to request clarification or add additional context in comments.

4 Comments

With your solution, My alert dialog says [object Object].
In fact see edit this time. Apparently you are getting an object inside an array inside an array, you should probably change your code a bit :)
Okay, this is making sense now. I was able to shave off one of the arrays by passing in $this->ajax->getRecArray() directly in in my JSON_encode() function as an argument.
If you only need one row from getRecArray, I think you can chop the second array by returning $row[0] instead of $row in getRecArray(), give it a try.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.