I have a php page that connects to mysql database, performs a query, stores its result as an array as a session variable.
$_SESSION['array1']=$array1;
This variable is received by another php page within same directory like this:
session_start();
$array1= $_SESSION['array1'];
Now, in the same php page itself, I have a javascript code that intends to access this $array1 and print its value. I found similar questions online and got to know about json_encode function but couldn't get it done. Code:
<script type="text/javascript">
var jsarray= <?php json_encode($array1); ?>;
document.write (jsarray[2]); </script>
I am just trying to print the 2nd index of array through javascript but haven't been able to do so. Nothing is displayed at all. I can see that I can print array on the second page using php but I need javascript code to be able to access the array. If I provide values to jsaraay in javascript code like:
var jsarray=[1,2,3,4,5];
and i print 2nd index,
document.write(jsarray[2]);
The output is correct. I want to access php array the same way. Please help?
$_SESSION['array1'][2]
isn't working for you? – Marc B Aug 13 '14 at 20:04