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


i can sucessfully pass index array javascript function below code. 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 want change array associative array. however, doesn't work more...

is there problem code ?

how should fix it? thank !

my code 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> 

the quotes in generated json confuse html parser. need entity encode contents of tag attributes. can use htmlspecialchars() or htmlentities() 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> 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -