** Update - While my solution works (and I haven't yet heard why not to use htmlspeciatchars()), I am including a modified version of Jacob Mouka's creative solution which successfully avoids having to use it. **
I am trying to pass an array of strings to javascript via onClick() using json_encode. Just passing json_encode($array) did not work. I surmised that since json_encode($array) returns ["a","b","c"], the quotes were the issue. I was successful with wrapping the json_encode($array) with htmlentities() and then using JSON.parse(array) to turn the string back into an array.
I read all the posts on this site and none showed this combination as a solution and I wonder if I am making it more complicated than it should be. Is htmlentities() the correct function to use? Is there a simpler way of sending this array from an onclick() to a javascript function? Thanks in advance.
Javascript
<script>
function shohmultiple(array){
alert("Aray as string: " + array);
array = JSON.parse(array)
for (i=0; i< array.length; i++){
alert(array[i]);
}
}
</script>
<?php $array=array("a", "b", "c"); ?>
HTML
<a href="#" onClick="shohmultiple('<?php echo htmlspecialchars(json_encode($array)) ?>')">Click Here</a>
Modified Solution from Jacob Mouka (for the workflow I am seeking)
Javascript
<script type="text/javascript">
function shohmultiple (array) {
for (i=0; i< array.length; i++){
alert(array[i]);
}
}
</script>
HTML
<?php $array = array("a", "b", "c"); ?>
<script>
// calling this before outputting <a href> works
<?php echo "var js_array = " . json_encode($array) . ";"; ?>
</script>
<a href="#" onClick="shohmultiple(js_array);">Click Here</a>