Ed Chen
Ed Chen

Reputation: 145

How to pass an php associative array as argument to Javascript function with json_encode()

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>

Upvotes: 1

Views: 1092

Answers (1)

RichGoldMD
RichGoldMD

Reputation: 1282

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>

Upvotes: 4

Related Questions