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.

6
  • what is loadInnerHTML? Commented Jan 27, 2014 at 15:00
  • 1
    You're sending a JSON string to loadInnerHTML(), not an array. Either remove the '' around <?php $disArray ?> or parse the string into an array with JSON.parse() Also, you're not echoing the variable. Commented Jan 27, 2014 at 15:01
  • its a javascript function. I'm trying to pass a php array to a different page using ajax. Commented Jan 27, 2014 at 15:01
  • You need to decode Json coming from php. read : [enter link description here][1] [1]: stackoverflow.com/questions/4935632/… Commented Jan 27, 2014 at 15:03
  • @user976990 Uh, no. If you hand it to javascript right (see my answer below) you don't need to decode. Commented Jan 27, 2014 at 15:05

2 Answers 2

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

Comments

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  ) ?>' );

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.