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) ?>");

The escape method

To build proper javascript literals and function call parameters from php you should escape your values with addslashes() before echoing them out. Make sure you surround the javascript literal or parameter value with double quotes. Single quotes cannot parse slashed escaped values.

   $myList = "bob, joe, o'reilly";
   $title = 'And he said "a peck of pickles"';

<script type="text/javascript">
    var list = "<?php echo addslashes($myList) ?>";
     callSomeFunc("<?php echo addslashes($title) ?>");

Will display in source as

<script type="text/javascript">
    var list = "bob, joe, o\'reilly";
     callSomeFunc("And he said \"a peck of pickles\"");

Leave a comment