WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I placed a javascript inside a .php file

$script = "<script type='text/javascript'>
        jQuery( document ).ready( function($) {         
            $(document).ready(function() {
              $('#particles').particleground({
                dotColor: '<?=json_encode($dotcolor)?>',
                lineColor: '#5cb9bd',                   
              });
            });
        }
     );
    </script>";

and tried to use <?=json_encode($dotcolor)?> to echo a variable. But it isn't working.

Any idea what I'm doing wrong?

share|improve this question
up vote 1 down vote accepted

This should work:

<?php $script = "<script type='text/javascript'>
        jQuery( document ).ready( function($) {         
            $(document).ready(function() {
              $('#particles').particleground({
                dotColor: " . json_encode($dotcolor) . ",
                lineColor: '#5cb9bd',                   
              });
            });
        }
     );
    </script>";
    ?>

Note: Its a better practice to enqueue Javascripts with wp_enqueue_script() and include dynamic strings via wp_localize_script().

Docs: https://codex.wordpress.org/Function_Reference/wp_enqueue_script https://codex.wordpress.org/Function_Reference/wp_localize_script

share|improve this answer
    
Thank you; it's working flawlessly! – kiarashi Apr 8 '15 at 9:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.