0

I'm trying to create a javascript tracker that can be included on any page, that will pass the variables "ref" and "aff" from the URL to the PHP code that does the tracking.

This code works perfectly for my purposes on PHP pages:

<script type="text/javascript" src="//www.foo.com/reftracker.php?ref=<?= $_GET['ref'] ?>&amp;aff=<?= $_GET['aff'] ?>">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="//www.foo.com/reftracker.php?ref=<?= $_GET['ref'] ?>&amp;aff=<?= $_GET['aff'] ?>"/>
</div>
</noscript>

The issue is that I also need to add the tracker to non-PHP pages, so I need a pure Javascript solution to pass those URL parameters into src attributes.

[EDIT]

For anyone interested, here is the solution I ended up with:

<script type="text/javascript">
    function fooParamParse(val) {
        var result = '', tmp = [];
        location.search.substr(1).split("&").forEach(function (item) {
            tmp = item.split("=");
            if (tmp[0] === val) result = decodeURIComponent(tmp[1]);
        });
        return result;
    }

    var script = document.createElement('script');
    document.getElementsByTagName('head')[0].appendChild(script);
    script.src = "//www.foo.com/reftracker.php?ref="+fooParamParse('ref')+"&amp;aff="+fooParamParse('aff')+"";
</script>
Colin M
  • 139
  • 1
  • 12
  • duplicate of http://stackoverflow.com/questions/5448545/how-to-retrieve-get-parameters-from-javascript / http://stackoverflow.com/questions/827368/using-the-get-parameter-of-a-url-in-javascript ..and i fear the solution is still up-do-date and best practice: pull everything from `document.location` – xerx593 Apr 18 '15 at 10:56

1 Answers1

2

You will need a pure javascript solution for that. Read here on how to read the GET parameters from url in javascript

Then add the follwing js code

var script = document.createElement('script');
document.getElementsByTagName('head')[0].appendChild(script);
script.src = "//www.foo.com/reftracker.php?ref="+GET['ref']+"&amp;aff="+ GET['aff']+"";
// assuming the GET parameters from javascript are stored in a hash GET
Community
  • 1
  • 1
Nikos M.
  • 8,033
  • 4
  • 36
  • 43