Passing a PHP array to an external Javascript function as an array

I do what I need to pass an array from my php to a function in external javascript. I am currently doing some tests that look like this:

<input type="text" onclick="show_error_message('<?php echo $array_sample ?>')" readonly="readonly"> 

and the javascript function is:

 function show_error_message(test) { alert(test) } 

my $ array_sample contains data that is array("1","2","3"); but the warning returned will be Array and whenever I change $array_sample to $array_sample[0] when passing parameters, I get data that is 1 as a warning. I wonder how I can pass the whole array to this to get the array in javascript as well. As you can see, I decided that this is a pop-up message for error handling, so I need it to be dynamic.

+4
source share
3 answers

Use json_encode

 onclick='show_error_message(<?php echo json_encode($array_sample) ?>)' 

or

 onclick="show_error_message(<?php echo htmlspecialchars(json_encode($array_sample)) ?>)" 

Note the absence of quotes ( ' ) around the php code, so the array literal is passed to show_error_message , not the string.

+9
source

Encoding a PHP array for json data using the json_encode() function.

And in Javascript, use JSON.parse() to parse the Json string.

+4
source

The code below shows how to pass a php array to javascript:

 <script type="text/javascript"> function mufunc(a) { var temp = new Array(); temp = a.split('~'); for(i=0;i<temp.length;i++) { alert(temp[i]); } } </script> <?php $a = array('a','b','c'); $b = implode("~",$a); ?> <a href="javascript:void(0)" onClick="mufunc('<?php echo $b; ?>')">Click Here</a> 
+4
source

Source: https://habr.com/ru/post/1442679/


All Articles