up vote 1 down vote favorite
share [fb]

I have a php multidimensional array populated from a table using the following code:

<?php starts

$array = array();
$i = 0;

while($row = mysql_fetch_array($result))
{

$array[$i] = array("handle" => $row['handle'],"firstname" => $row['first_name'],"lastname" => $row['last_name']);
$i++;
}

echo json_encode(json_encode($array));

?> php ends

this is called by .post from jQuery and when I alert() the data returned I get the following output:

[
{"handle":"admin","firstname":"admin","lastname":"admin"},
{"handle":"ms","firstname":"ms","lastname":"ms"},
{"handle":"op","firstname":"op","lastname":"op"},
{"handle":"ui","firstname":"ui","lastname":"ui"}
]

the Jquery code I use to extract the php array is:

$.post("test1.php","",
            function(data){

                var obj = $.parseJSON(data);
                alert(obj);
                var obj2 = $.parseJSON(obj);
                alert(obj2);
                alert(obj2[1]);
                var result = eval(data);
                alert(result[0][0]);


    },"html");

alert(obj) gives me the output specified. alert(obj2) gives me:

[object Object],[object Object],[object Object],[object Object]

alert(obj2[1]) gives me:

[object Object]

How do I get at the data in this???

link|improve this question

57% accept rate
are you using firebug just use console.log to print objects – run Sep 12 '11 at 6:16
feedback

3 Answers

'[object Object]' is the toString() of an Object, which is implicitly called when using alert() (which alerts strings only).

You need to use dot notation to access it, or console.log() to view the object (provided your browser has a competent console).

link|improve this answer
feedback

Your first

var obj = $.parseJSON(data);

Should be all you need. You can then access your objects like:

obj[0]['handle']
// or
obj[0].handle
link|improve this answer
feedback

To view any object details in IE9 use - console.dir(obj)

Where as in Firefox, you can use - console.log(obj)

Remember, the details will be written in the console (present in Developer Tools in IE and Firebug in Firefox)

Using console statments you can view your object structure and then you can access any property of object using '.' dot operator.

Hope this helps.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.