0

I have a php array of this type

[0] => Array
        (
            [id] => 22
            [lat] => 40.8434169
            [lng] => 11.409390199999962
        )

and I wish to pass it to a js file in body-onload.

I tried these ways:

1) <body onload="addMarkers(<?php print_r($myArray) ?>)">
2) <body onload="addMarkers(<?php echo json_encode($myArray) ?>)">

but without success

EDIT: I solved in this way

<script type="text/javascript">
    var myJsArray = <?php echo json_encode($myArray) ?>;
</script>
Tab
  • 309
  • 2
  • 7
  • 16
  • Approach 2 should work. – Felix Kling Aug 23 '13 at 18:18
  • Also, [learn how to **debug** JavaScript](http://www.netmagazine.com/tutorials/javascript-debugging-beginners). Maybe the console gives you a clue why it "does not work". – Felix Kling Aug 23 '13 at 18:22
  • While approach 2 *should* work, it doesn't make it right. Use AJAX to retrieve an array from a server page, it's cleaner and you decouple your php from your js files. – ILikeTacos Aug 23 '13 at 19:36

3 Answers3

0

I am not sure what your addMarkers() function does, but this might work:

<body onload="addMarkers(<?php echo implode(', ', $myArray); ?>)">
Jordi Jolink
  • 461
  • 3
  • 7
  • That probably won't work since the first element of the array is an array itself. So `echo implode(', ', $myArray);` would result in the string `"Array"` or `"Array, Array"` if there are multiple. – Felix Kling Aug 23 '13 at 18:21
0
<?php echo json_encode($myArray) ?>

Should work just fine. Open a development console and see what the JS interpreter has to say about the outputed code.

Sergiu Paraschiv
  • 9,929
  • 5
  • 36
  • 47
0

first option you tried wont work in any case.But the second one is valid and passes a json object to your function

addMarkers(<?php echo json_encode($myArray) ?>)

If this doesnt work, error will be due to the reason that the addMarkers function doesnt expect an json object as its argumet. You can see this error description in your firebug console. Also you can check the function defintion to find out the expected argument.

Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101