1

I can sucessfully pass an index array to the javascript function with below code. For example:

<?php
$arr = array(1, 2, 3);
?>
<button onclick="test(<?=json_encode($arr)?>);">test</button>
<script>
function test(x){
  alert(x[0]);
  alert(x[1]);
  alert(x[2]);
}
</script>

Now I want to change the array to be an associative array. However, it doesn't work any more...

Is there any problem with my code ?

How should I fix it? Thank you very much !

My code is as below:

<?php
$arr = [ "A" => 1, "B" => 2, "C" => 3 ];
?>
<button onclick="test(<?=json_encode($arr)?>);">test</button>
<script>
function test(x){
  alert(x["A"]);
  alert(x["B"]);
  alert(x["C"]);
}
</script>
3
  • 1
    Possible duplicate of convert php associative array into javascript object Commented Jul 26, 2017 at 3:47
  • @AlexanderNied Its answer is use json_encode(), which is just what I'm trying to do. Commented Jul 26, 2017 at 3:57
  • Sorry, my mistake. Commented Jul 26, 2017 at 4:00

1 Answer 1

4

The quotes in the generated JSON confuse the html parser. You need to entity encode the contents of tag attributes. You can use htmlspecialchars() or htmlentities() for this:

<?php
$arr = [ "A" => 1, "B" => 2, "C" => 3 ];
?>
<button onclick="test(<?=htmlentities(json_encode($arr))?>);">test</button>
<script>
function test(x){
  alert(x["A"]);
  alert(x["B"]);
  alert(x["C"]);
}
</script>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your suggestion ! But the alert message shows "undefine". It doesn't show the value of the array...
Strange - its working perfectly for me. Can you view source in your browser and share?
Oops...sorry .... I just got a typo... It works now !!!! Thank you so much !!!!!!!!!

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.