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.

7
  • 2
    post relevant code Commented Jun 22, 2018 at 8:57
  • 1
    Possible duplicate of Access PHP variable in JavaScript Commented Jun 22, 2018 at 8:57
  • Put in to an input? Store it as a cookie? Make use of AJAX? echo (output) it? Commented Jun 22, 2018 at 8:57
  • Refer to How do I ask a good question? Commented Jun 22, 2018 at 8:58
  • 1
    Please visit the help center, take the tour to see what and How to Ask. Do some research, search for related topics on SO; if you get stuck, post a minimal reproducible example of your attempt, noting input and expected output. Commented Jun 22, 2018 at 8:58

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

Comments

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})

1 Comment

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]

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.