Passing a Value from PHP to Javascript Variable

When inserting a value from PHP script into javascript code you should be careful to properly format the text so it will not break your javascript. These are two ways of properly formatting the text to be inserted into a javascript variable.

You can first url encode the value in php then decode it in javascript. Try something like this from your php script.


<script type="text/javascript">
    var list = decodeURIComponent("<?php echo rawurlencode($mySelectList) ?>");
</script>

If you have PHP 5.2 + you can use json_encode to properly escape the text. It will also put in the outer quotes for the value for you.


<script type="text/javascript">
    var list = <?php echo json_encode($mySelectList) ?>;
</script>

Leave a comment

0 Comments.

Leave a Reply


[ Ctrl + Enter ]