I understand that the format for passing a PHP array to Javascript is:
<script type="text/javascript">
var obj = <?php echo json_encode($php_variable); ?>;
</script>
I have a php function that stores some values in a longitude and latitude array. These array do hold the right values within php since print_r() within php shows me that the array is correct.
print_r($latitude_array);
print_r($longitude_array);
Now, I pass on this array to JS in this manner:
<script>
var lati_array = "<?php echo json_encode($latitude_array); ?>";
var longi_array = "<?php echo json_encode($longitude_array); ?>";
alert(lati_array[0]);
</script>
In the beginning, when I open the HTML file, it shows me an empty array (which is expected because the PHP arrays aren't filled yet). Then user enters something, the php arrays are filled up with longitudes and latitudes. These values should now be passed to JS. However, it doesn't alert anything after that. I can't be sure if array is successfully passed to JS. What am I missing?
-
What is the way you are triggering this code after user filling the details?Thamilhan– Thamilhan2015年11月17日 07:00:25 +00:00Commented Nov 17, 2015 at 7:00
-
The PHP, HTML and JS are all part of the same file. The PHP takes values from the user -- searches in a local file based on those values and comes up with longtitudes and latitudes. Now, I'm trying to pass this to JS because I want to mark them on GoogleMaps.learnerX– learnerX2015年11月17日 07:02:30 +00:00Commented Nov 17, 2015 at 7:02
3 Answers 3
Try this:
<script>
var data = <?php echo json_encode( $data ); ?>;
</script>
4 Comments
" (double quotes lead to invalid JSON format) @VictoriaFrenchTry like below:
<?php
$array_var = array(111, 222, 333, 444);
?>
<script>
var array_var = "<?php echo json_encode($array_var); ?>";
console.log(array_var);
array_var = JSON.parse(array_var);
console.log(array_var);
alert(array_var[0]);
</script>
Comments
You are getting a string in lati_array , Try to convert it into json like this:
<script>
var lati_array = "<?php echo !empty($latitude_array) ? json_encode($latitude_array) : ''; ?>";
var longi_array = "<?php echo !empty($longitude_array) ? json_encode($longitude_array) : ''; ?>";
lati_array = JSON.parse(lati_array);
alert(lati_array[0]);
</script>