0

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?

8
  • $_SESSION['array1'][2] isn't working for you? Commented Aug 13, 2014 at 20:04
  • Have you tried turning the data into JSON using json_encode? php.net/manual/en/function.json-encode.php Commented Aug 13, 2014 at 20:04
  • Try json_encode($array1); Commented Aug 13, 2014 at 20:05
  • Try JSON.prase() on your js var. Commented Aug 13, 2014 at 20:06
  • @MarcB $_SESSION works to get the variable in php but not in javascript. I want to access using that. Commented Aug 13, 2014 at 20:09

3 Answers 3

0

If i write

$array = [1, 2, 3];
print('<script> jsarray = ' . json_encode($array) . ';</script>');

then I can access jsarray in my javascript.

Note that jsarray[2] wil return the 3rd index, not the 2nd (indices start at 0). You can also check your javascript console (F12 on Chrome + Firefox, then select console tab) for errors.

0

You need to echo the json:

var jsarray= <?php echo json_encode($array1); ?>;

Online sample here.

0
-1

try this way:

<script>
var jsArray = ["<?php echo join("\", \"", $array1); ?>"];
alert(jsArray);
</script>

That should work

1
  • bad bad BAD idea. You never dump text from php directly into a JS context. You use json_encode(), always. One JS metacharacter anywhere in the PHP output and you introduce a JS syntax error which completely kills the <script> block. Commented Aug 13, 2014 at 20:11

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.