1

my php code looks like this:

$result['firstName']['lastName']='johan';
echo json_encode($result);

how should i type to use this array in javascript with jquery?

...function(data) {
    alert(data.firstName.lastName);
});

or

...function(data) {
    alert(data.firstName['lastName']);
});
1
  • Did you try those out? Experiment! Experimentation never did any harm, ever. Not once. :P Commented Feb 4, 2010 at 22:00

4 Answers 4

4

JQuery doesn't effect object access, so you can just do

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

3 Comments

In my case after echo the $data i got an alert johan :-)
what do you mean with "doesn't affect object access"
@noname, I was just saying that introducing jQuery doesn't change the situation.
2

Javascript doesn't technically have associative arrays, so technically in Javascript you're working with an Object. Either syntax you used should work.

1 Comment

Technically, every instance of Object is an associative array.
2

The object['property'] syntax is only needed in javascript for numbers or syntactically ambiguous keys (e.g. those containing spaces).

Comments

1

This worked for me but its very ugly

<?php

$result['firstName']['lastName']='johan';
$data =  json_encode($result);

?>
<html>
<body onload='myfunction(<?php echo $data; ?>);'>
<script>
function myfunction(data) 
{
alert(data.firstName.lastName);
}
</script>
</body>
</html>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.