0

I have this array:

$men['display']=array( 
                  "edit"        =>"1", 
                  "description" =>"2", 
                  "phone"       =>"3", 
                  "mail"        =>"4" 
                 );

I tried to transfer it to javascript by using:

<?php $disArray = json_encode($men['display']);?>

then, I sent it to javascript:

<select id="selectBoxHere" onChange="loadInnerHTML('<?php $disArray ?>')";>

For some reason, my javascript function 'loadInnerHTML' dosen't send my array to javascript.

  • what is loadInnerHTML? – scrblnrd3 Jan 27 '14 at 15:00
  • 1
    You're sending a JSON string to `loadInnerHTML()`, not an array. Either remove the `''` around `` or parse the string into an array with `JSON.parse()` Also, you're not echoing the variable. – crush Jan 27 '14 at 15:01
  • its a javascript function. I'm trying to pass a php array to a different page using ajax. – user3164596 Jan 27 '14 at 15:01
  • You need to decode Json coming from php. read : [enter link description here][1] [1]: http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript – cyberpro4 Jan 27 '14 at 15:03
  • @user976990 Uh, no. If you hand it to javascript right (see my answer below) you don't need to decode. – jszobody Jan 27 '14 at 15:05
  • When i remove the '' around the php code i get: Uncaught SyntaxError: Unexpected token ; – user3164596 Jan 27 '14 at 15:09

2 Answers2

3

You forget the echo statment.

And if you use single quotes, it makes this a string. For a javascript object you don't need the single quotes, json_encode will ensure it is javascript safe.

loadInnerHTML(<?php echo $disArray ?>)

I'd also recommend that you store this variable directly in javascript first, rather than passing it into a function. Otherwise you have to worry about double quotes inside double quotes, breaking your <select> tag.

var disArray = <?php echo $disArray ?>;

Then you can just use that variable.

loadInnerHTML(disArray)
jszobody
  • 28,495
  • 6
  • 61
  • 72
0

Echoing an array in php will result in

var dis_array = Array

which js couldn't understand. Try:

var disArray = JSON.parse( '<?php echo json_encode( $disArray  ) ?>' );
cyberpro4
  • 1
  • 1