0

I extracted data from a CSV file using PHP and stored the data as a nested array. I stored this array as a session variable and now I want to access the array in another html file using javascript. How can this be done?

<?php
    session_start();
    $arr=array();

    $arr['1']=array('abc','def');
    $arr['2']=array('123','456');

    $_SESSION["abc"]=$arr;

?>

This is a sample php. I have to access the session variable in javascript.

2 Answers2

2

Yes, you can use implode PHP function to convert your array to string and then echo that string and assign to a JS variable like in example below.

Your another HTML file:

<?php 
    session_start();
    $your_array=$_SESSION['your_array'];
?>
<script>
    var js_variable = [<?php echo implode($your_array,','); ?>];
    console.log(js_variable);
</script>
Aleksey Solovey
  • 4,153
  • 3
  • 15
  • 34
Deepak Vaishnav
  • 357
  • 3
  • 15
0

What you should be aware of, is that php is server side and javascript is client side. So to solve this, you have 2 options:

  1. let the php code add this variables in the head. on to of everything:

    <script>
      var php_variables= <?php echo json_encode($your_php_variables); ?>;
    </script>
    

or 2. Make a seperate php file which just echos only the value in json and put a json header:

 <?php 
  header("content-type:application/json");
  echo json_encode($your_php_variables);
 ?>

and then let javascript retrieve it. there are many libraries available for that. but lets take a comon one like jquery:

$.get("yourphpfile.php",function(data){do something here})
Mark Smit
  • 582
  • 4
  • 12
  • Your first method helped in retrieving the array into javascript. I confirmed it by doing console.log(). But doing document.write of the variable is giving [object Object] – Akshay Bharadwaj Jun 22 '18 at 11:05