0

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?

2
  • What is the way you are triggering this code after user filling the details? Commented 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. Commented Nov 17, 2015 at 7:02

3 Answers 3

3

Try this:

<script>
    var data = <?php echo json_encode( $data ); ?>;
</script>
Sign up to request clarification or add additional context in comments.

4 Comments

legotin is correct, don't wrap the array in quotes, otherwise you have a javascript string and not an array.
I changed it a little, try again please
@legotin You were right. That worked for me. Shouldn't have included the quotes in there.
Nope that's not the case over here " (double quotes lead to invalid JSON format) @VictoriaFrench
0

Try 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

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.