Pages

Friday, February 15, 2013

Pass a PHP array to a JavaScript function


Use JSON.
In the following example $php_variable can be any PHP variable.
<script type="text/javascript">
    var obj = <?php echo json_encode($php_variable); ?>;
</script>
In your code, you could use like the following:
drawChart(600/50, <?php echo json_encode($day); ?>, ...)
In cases where you need to parse out an object from JSON-string (like in an AJAX request), the safe way is to use JSON.parse(..) like the below:
var s = "<JSON-String>";
var obj = JSON.parse(s);

No comments:

Post a Comment