Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

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?

share|improve this question
    
$_SESSION['array1'][2] isn't working for you? – Marc B Aug 13 '14 at 20:04
    
Have you tried turning the data into JSON using json_encode? php.net/manual/en/function.json-encode.php – Michael Aug 13 '14 at 20:04
    
Try json_encode($array1); – Thomas Powers Aug 13 '14 at 20:05
    
Try JSON.prase() on your js var. – n00b Aug 13 '14 at 20:06
    
@MarcB $_SESSION works to get the variable in php but not in javascript. I want to access using that. – vaib1237 Aug 13 '14 at 20:09

3 Answers 3

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.

share|improve this answer

You need to echo the json:

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

Online sample here.

share|improve this answer
    
Tried that as well. Did't work. No output at all. – vaib1237 Aug 13 '14 at 20:12

try this way:

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

That should work

share|improve this answer
    
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. – Marc B Aug 13 '14 at 20:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.