Efrain Efrain - 2 years ago 60
Javascript Question

How can I grab a URL string inside a directory?

I'm using this code to grab Google's utm_campaign from the URL to insert it in a hidden form field:

<script type="text/javascript">
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
function onLoad() {
var value = getQueryVariable("utm_campaign");
var e = document.getElementById('keyword');
e.value = value;

The code works great in the root URL but when I use it inside a subdirectory it stops working.

site.com/?utm_campaign=test - Works

site.com/directory/?utm_campaign=test - Does not work

How can I grab a URL string inside a directory?


Answer Source

That code should function exactly the same whether you are on the root url or in a subdirectory.

In your case (based on the example lined in your comment), it appears that the onLoad function is only getting run on your root url because the body tag is defined as <body onload="onLoad()">

In order to have the onLoad function executed on your subdirectory pages, you'll need to include onload="onLoad()" in your body tag on those pages as well.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download