0

This is not a duplicate of How to pass variables and data from PHP to JavaScript?

After consulting the previous question, I have another :

My problem is that when I get the php array in Js, and I print it, I have just [object][object]

<?php 
    $tl = array(
         0=>array('a', 'b', 1),
         1=>array('c', 'd', 2)
    ); 
?>

and javascript :

<script type="text/javascript">
    var arr= <?php echo json_encode($tl ); ?>;

    for(var i=0;i<3;i++){
        alert(arr[i]);
    }
</script>
Community
  • 1
  • 1
phoenix
  • 127
  • 1
  • 10

4 Answers4

1

You should display it using console.log instead of alert :

console.log(arr[i]); //Check the result in you browser console

console.log : Formats your objects nicely and allows to traverse them.

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
1

Remember: You don't have more than 2 object in your array so you should not run loop more than 2 times. first loop give you permission to access the object of array then you can run a loop to show/get the property of object.

 <?php 
   $tl = array(
      0=>array('a', 'b', 1),
      1=>array('c', 'd', 2)
  ); 
?>

var arr = ;

for(var i=0;i<2;i++){
    for(var j=0;j<3;j++){
        alert(arr[i][j]);
        console.log(arr[i][j]);// you can also show the value from the console of your browser
  }
}

output of console

enter image description here

Mahfuz Ahmed
  • 721
  • 9
  • 23
0

Try this ;)

alert() shows type if not basic data type. In your case it's Object that's why it's showing [object][object]

To debug JavaScript one should use console.log() and other console methods like:

console.log();
console.debug();
console.warn();
console.error();

etc.

One more thing here you are trying to access values of nested array so you can go with alert like this:

var arr= <?php echo json_encode($tl ); ?>;
for(var i=0;i<3;i++){
    alert(arr[i][0] + " " + arr[i][1] + " " + arr[i][2]);
}    

OR

Use nested loop to iterate inner array values;

itzmukeshy7
  • 2,669
  • 1
  • 21
  • 29
-3

try this:

<input type="hidden" id="array" value="<?php echo json_encode($tl); ?>" /> 

then use

<script type="text/javascript">
var arr = getElementById('array').value
for(var i=0;i<3;i++){
    alert(arr[i]);
}
</script>
Gerald Schneider
  • 17,416
  • 9
  • 60
  • 78