Passing PHP Array Into External Javascript Function As Array
I'm doing something which I need to pass an array from my php to a function on an external javascript. I'm currently doing some test right now which looks like this:
Solution 1:
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)) ?>)"
Notice the lack of quotes('
) around the php code, this way an array literal is passed to show_error_message
and not a string.
Solution 2:
Encode PHP array to json data using json_encode()
function.
And in Javascript use JSON.parse()
to parse the Json string.
Solution 3:
The below code shows how to pass 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>
Post a Comment for "Passing PHP Array Into External Javascript Function As Array"