Storing Php $_get Variable In A Javascript Variable?
Solution 1:
Since $_GET
just access variables in the querystring, you can do the same from javascript if you wish:
<script>var $_GET = populateGet();
functionpopulateGet() {
var obj = {}, params = location.search.slice(1).split('&');
for(var i=0,len=params.length;i<len;i++) {
var keyVal = params[i].split('=');
obj[decodeURIComponent(keyVal[0])] = decodeURIComponent(keyVal[1]);
}
return obj;
}
</script>
Solution 2:
Original answer:
In your .php file.
<scripttype="text/javascript">var team1, team2;
team1 = <?phpecho$_GET['team1']; ?>;
team1 = <?phpecho$_GET['team1']; ?>;
</script>
Safer answer:
Didn't even think about XSS when I blasted this answer out. (Look at the comments!) Anything from the $_GET array should be escaped, otherwise a user can pretty much insert whatever JS they want into your page. So try something like this:
<scripttype="text/javascript">var team1, team2;
team1 = <?phpecho htmlencode(json_encode($_GET['team1'])); ?>;
team1 = <?phpecho htmlencode(json_encode($_GET['team1'])); ?>;
</script>
More about XSS from Google http://code.google.com/p/doctype/wiki/ArticleXSSInJavaScript.
Cheers to the commenters.
Solution 3:
Make sure you use something like htmlentities to escape the values so that your application is not susceptible to cross-site scripting attacks. Ideally you would validate the variables to make sure they're an expected value before outputting them to the page.
<scripttype="text/javascript">var team1 = '<?phpecho htmlentities($_GET['team1']); ?>';
var team2 = '<?phpecho htmlentities($_GET['team2']); ?>';
</script>
Solution 4:
<scripttype="text/javascript">var team1 = <?phpecho$_GET['team1'] ?>;
var team2 = <?phpecho$_GET['team2'] ?>;
</script>
Solution 5:
Another way to do this with javascript :
var team1 = $_GET('team1');
function$_GET(q,s) {
s = s ? s : window.location.search;
var re = newRegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
}
Post a Comment for "Storing Php $_get Variable In A Javascript Variable?"