PHP $_GET in JavaScript

This other day I encountered a situation where I needed to pass in variables to a javascript. I had built the javascript in a PHP file before, and could easily use PHP to inject the variables like this:

var name = "<?php echo $name ?>"

But when I wanted to separate the javascript from PHP I could not access the PHP variables anymore, the solution was to do it like this:

<script src=”my_script.js?name=<?php echo $name ?>” ></script >

and then access the variable from the script by $_GET.name

The code on jsfiddle:
http://jsfiddle.net/ctncP/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: