I have an array in php lets call it:
$nums = array(10,25,52,32,35,23);
I want to send it to my javascript function like this:
var nums=[10,25,52,32,35,23];
How can i do this? (My javascript file name is "nums.js")
Edit:
nums.js is a javascript code. It changes the values of table in the html. But the values only exist in php. So i have to send the values to javascript.
4 Answers 4
PHP>= 5.2
The json_encode function is for this purpose:
<?php echo 'var nums=' . json_encode(array(10,25,52,32,35,23)) . ';'; ?>
Docs: http://php.net/json_encode
PHP < 5.2
If you can't use json_encode, take a look at this post for a way to define an equivalent.
4 Comments
<script> var nums = "<?php echo json_encode(array(10,20)); ?>"; nums = JSON.parse(nums); </script><script src="nums.js"></script>As long as your javascript file is being parsed by PHP before being sent to the client, then this should work:
<?php echo "var nums=[" . implode(',', $nums) . "];"; ?>
7 Comments
json_encode(). Among other things this will make sure values are properly escaped and data types are properly sent.Just json_encode() the array and then output it as an array literal in javascript.
<?php
$nums = array(10,25,52,32,35,23);
$nums_json = json_encode($nums);
?>
<script type="text/javascript">
var nums = <?php echo $nums_json; ?>;
</script>
Comments
you can also use json_encode() but only possible from php 5.2 see more: https://www.php.net/manual/fr/function.json-encode.php
or you can use this function:
function php2js ($var) {
if (is_array($var)) {
$res = "[";
$array = array();
foreach ($var as $a_var) {
$array[] = php2js($a_var);
}
return "[" . join(",", $array) . "]";
}
elseif (is_bool($var)) {
return $var ? "true" : "false";
}
elseif (is_int($var) || is_integer($var) || is_double($var) || is_float($var)) {
return $var;
}
elseif (is_string($var)) {
return "\"" . addslashes(stripslashes($var)) . "\"";
}
return FALSE;
}
1 Comment
json_encode(), not to use it as an afterthought. Even if you don't have native PHP json_encode() there are PHP libraries out there to do this for you. You should not be manually building the JSON representation from the array.