views:

85

answers:

1

My understanding is that in order to return a complex PHP variable to Javascript, it should be done via AJAX and json_encode. Could somebody give me an actual example (both PHP and Javascript code) of this? Lets say we have the two-dim array in PHP:

$twoDArr = array( array('Greg', 44, 'Owner'),
                  array('Joe', 23, 'Renter'),
                  array('Susan', 39, 'Owner'),
                  array('John', 32, 'Renter)
                );

How would we return this to an analogous two dimensional array in javascript using json_encode?

A: 
<?php

$twoDArr = array( array('Greg', 44, 'Owner'),
                  array('Joe', 23, 'Renter'),
                  array('Susan', 39, 'Owner'),
                  array('John', 32, 'Renter)
                );
?>

<script>
twoDArr = JSON.parse(<?=json_encode($twoDArr)?>)
alert(twoDArr[0][0]) //alerts 'Greg'
alert(twoDArr[0][1]) //alerts '44'
alert(twoDArr[1][0]) //alerts 'Joe'
</script>
tipu
While this example certainly works, it is generally best to avoid eval when a simple alternative is present. In this case, you could replace the eval statement with JSON.parse(<?=json_encode($twoDArr)?>) to achieve the same effect.
Rookwood
@Rockwood: I edited my answer to reflect your suggestion
tipu
Sorry for being so obtuse...you have "JSON.parse(<?=json_encode($twoDArr)?>)" What's with the "?=" is that some sort of shorthand? I tried this in my sample page and I get nothing coming back.
GregH
Something weird is up...if I echo out json_encode($twoDArr) I get:[["Greg",44,"Owner"],["Joe",23,"Renter"],["Susan",39,"Owner"],["John",32,"Renter"]] That isn't right is it? Should the arrays be separated by a ":"?
GregH
Ok, I figured out the problem. I'm not sure why, but the php variable has to be double encoded with JSON_ENCODE. So the JSON.parse line should read: var twoDArr=JSON.parse(<?php echo JSON_ENCODE(JSON_ENCODE($twoDArr))?>);
GregH