lisovaccaro
lisovaccaro

Reputation: 33956

How do I pass a variable to my scripts .js file?

This is in my head:

<script>
var uid = "<?=$uid;?>";
</script>

I need to use "uid" on my .js file but I don't know how. Is there an easy way to retrieve it?

Upvotes: 0

Views: 101

Answers (2)

Devin Burke
Devin Burke

Reputation: 13820

As long as your put that <script> before your <script src=""> that links to your .js file, the variable is within scope in that file. However, any page that does not declare the uid variable but references that script file will error.

Remember, the variable has to be declared before a separate file can use it:

<script>
var uid = "<?=$uid;?>";
</script>
<script type="text/javascript" src="script.js"></script>

Upvotes: 1

Mitch Dempsey
Mitch Dempsey

Reputation: 39869

You can use it anywhere, just make sure this block is before you load any external javascript files.

Upvotes: 1

Related Questions