0

I a webpage written in php/html that adds the contents of a text box to a session array each time a submit button is pressed. What I need to be able to do is take the unknown number of elements in the session array and have access to each of them in the javascript portion of my code.

Here is the php portion of my code so far:

<?php
  session_start();

  if(!isset($_SESSION['answers']))
    $_SESSION['answers'] = array();
?>

<?php
 if (!empty($_POST['submit'])) {
  unset($_POST['submit']);
  $_SESSION['locations'][] = $_POST;
 }

 if (!empty($_POST['display'])){
  foreach ($_SESSION['locations'] as $array){
  echo "<script type='text/javascript'>alert('{$array['lat']}')</script>";
 }
}
?>

This will display each as an alert, but I need them as variables that can be accessed in javascript.

Thanks in advance

Ryan
  • 231
  • 3
  • 9

1 Answers1

1

Just encode your data as JSON. It will be parsed as JavaScript array/object literal by the browser:

var locations = <?php echo json_encode($_SESSION['locations']) ?>;

Having a variable for each element of the array is not a good solution.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Thank you, I am relatively unfamiliar with JSON though. How would I access the specific elements of the newly created JSON object? – Ryan Nov 27 '13 at 05:05
  • As I said, the generated code will be parsed array or object literal (because JSON can interpertreted as such). In JavaScript you access arrays with bracket notation, like `arr[0]`, `arr[1`], ... `arr[i]` and objects usually with dot notation, `obj.propertyName`, but you can also use bracket notation, `obj['propertyName']`. See http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json. – Felix Kling Nov 27 '13 at 05:12
  • When I use the following var loc = ; alert(loc[0]); in the javascript portion of my code, it breaks the code. – Ryan Nov 27 '13 at 05:22
  • 1
    @Ryan: Then you must be doing something wrong. Maybe you are not including those lines correctly. – Felix Kling Nov 27 '13 at 05:24