Xeos
Xeos

Reputation: 6487

Pre-set javascript variables from URL parameters

Imagine I have a script abc.js, which has one global variable userid. Several AJAX requests are made instantly after it is loaded (it can happen after or before DOM is parsed by browser). I need the script to have different variable value for different users. Requests has to be made instantaneously after JS is available. Here is what I am looking for:

Is there a way to do this with some Apache/Lighttpd extension? Since I can't rely on <script>userid=12345</script> at the begining of the document, as abc.js will most probably be executed before userid=12345 is evaluated.

Upvotes: 0

Views: 151

Answers (2)

Mike Brant
Mike Brant

Reputation: 71384

You can simply use PHP to output the javascript variables at a point before when the abc.js script is called. In this case the parameter would be passed to the main PHP script (i.e the page). Like this:

<script type="text/javascript">
var userid = <?php echo $_GET['userid']; ?>;
</script>
<script type="text/javascript" src="/js/abc.js">

Of course you probably want to sanitize the parameter value in PHP before using it.

Here, abc.js can just reference the value of userid in global scope. There is no need to pass userid to the script in URL and have Apache use PHP to dynamically generate the js file. In fact, you likely don't want that approach as it prevents optimal browser caching of the script.

If you don't want PHP involved you have other options to pass this data such as the URI parsing option presented by @yent, HTML5 localStorage, cookies, etc.

Upvotes: 1

yent
yent

Reputation: 1343

You can parse window.location.search and set window properties :

var p = window.location.search.substr(1).split(/&/);
if(p.length && p[0]) for(var i=0; i<p.length; i++) {
    var a = p[i].split(/=/);
    window[a[0]] = a[1];
}

Upvotes: 0

Related Questions