0
var testvr = <?php echo 5;?>;

When this is used in my javascript I get an "Unexpected token <" error on the line. I've seen countless examples of people setting a javascript variable like this so I'm a bit confused. I've seen some do it as

var testvr = "<?php echo 5;?>";

But that passes the code as a string to the variable. I'm really just looking for a way to simply set a javascript variable to something from php, nothing fancy at all it would just be a number such as 5.

5
  • 1
    Show some more code. And of course you have to call it from PHP script. Commented Sep 16, 2013 at 10:59
  • 3
    pass the code as a string to the variable and then parse it as int in javascript Commented Sep 16, 2013 at 11:00
  • There is no problem with the code provided there must some different error. you can share more code Commented Sep 16, 2013 at 11:07
  • Is this code in a .js or a .php file? Commented Sep 16, 2013 at 11:10
  • The problem was that it wasn't a .php file, been so long since I've used inline PHP I forgot that bit. Thanks for the quick responses! Commented Sep 16, 2013 at 11:14

2 Answers 2

2

When this is used in my javascript I get an "Unexpected token <" error on the line.

This means that you aren't passing the file through a PHP parser before delivering it to the browser.

Presumably you are placing the PHP in a .js file. Either rename that file to .php or configure your server to process your .js files with PHP.

Don't forget that PHP will default to sending Content-Type: text/html so make sure you include header("Content-Type: application/javascript");.

Sign up to request clarification or add additional context in comments.

Comments

1

It is safe to use an object:

<?php
   $vars = array('var1' => 'val1', 'var2' => 'val2', 'intvar' => 55);
?>

<script>
   var myvars = <?php json_encode($vars);?>
   console.log(myvars.var1);
   console.log(myvars.var2);
   console.log(myvars.intvar);
</script>

The above will keep numbers as numbers and all unsafe characters will get escaped.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.