$_GET in Javascript?

Mike

New member
Jun 27, 2006
6,777
116
0
51
On the firing line
Yes, I realize $_GET is a PHP thing, but it's the easiest way to describe what I want.

Very simple, I want to use javascript to do what PHPs $_GET [''] does, and then also use JS to write that value into my Goog Analytics code.

PHP version of what I'm doing on other pages:

Code:
<?php
$var1 = $_GET['var1'];  // nice, easy PHP grab the variable outta the URL
$var2 = $_GET['var2'];
$var3 = $_GET['var3'];
$var4 = $_GET['var4'];
$var5 = $_GET['var5'];
?>

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-xxxxxx-x']);
  _gaq.push(['_setDomainName', 'none']);
  _gaq.push(['_setAllowLinker', true]);
  _gaq.push(['_trackPageview']);
  _gaq.push(['_setCampNameKey', '<?php echo $var1; ?>']); // again...simple PHP, print out the variable
  _gaq.push(['_setCampSourceKey', '<?php echo $var2; ?>']);
  _gaq.push(['_setCampMediumKey', '<?php echo $var3; ?>']);
  _gaq.push(['_setCampTermKey', '<?php echo $var4; ?>']);
  _gaq.push(['_setCampContentKey', '<?php echo $var5; ?>']);
  _gaq.push(['_trackPageview']);


  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
I've spent the past 2 hours trying to find a good tutorial on this, and it seems that Javascript doesn't have a simple function like PHP to do it.

Anybody have any idea?
 


JavaScript query string - Stack Overflow

From there:

Code:
function getQueryString() {
  var result = {}, queryString = location.search.substring(1),
      re = /([^&=]+)=([^&]*)/g, m;

  while (m = re.exec(queryString)) {
    result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
  }

  return result;
}

// ...
var myParam = getQueryString()["myParam"];
 
Whenever I run into something that javascript sucks at/can't do I just just use PHP.

Sometimes it's as easy as document.write("<?php YURCODE ?>"); Sometimes it messes up and you have to play with it a bit.