Reputation: 63
So, I found this similar request, but the poster answered himself with going into details:
Persistent URL query string throughout the entire site?
Essentially, I have an event management website where I can edit html and javascript, but not php. I am trying to setup passing a discount code through a link to use for affiliate tracking. The system already allows for the code to be passed in a query in the form of:
https://www.example.com/reg/newreg.php?eventid=89335&discountcode=code
BUT
The caveat is that the system only allows that when linking the person directly into the registration process as shown above. Since no one is going to want to buy a ticket without seeing the event details, this is all but useless. The address of the homepage is in the form of:
https://www.example.com/home/89335
But when I try appending &discountcode=code to the address, the query string is lost upon clicking the registration link and going to the registration page.
Any suggestions on how to handle this?
Thanks!
Upvotes: 5
Views: 4059
Reputation: 326
You could try to parse all a-tags containing a href and update the href using javascript.
If you can use jQuery, you could do it that way (completely untested, so this could not work directly, but you should get the way to the solution :))
To get the url param, you could use the solution from here: https://stackoverflow.com/a/5158301/2753126
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
jQuery(document).ready(function ($) {
var persistedQueryParam = getParameterByName('discountcode');
if (persistedQueryParam && persistedQueryParam.length > 0) {
$('a[href]').each(function () {
var elem = $(this);
var href = elem.attr('href');
elem.attr('href', href + (href.indexOf('?') != -1 ? '&' : '?') + 'discountcode=' + persistedQueryParam);
});
}
});
Just replace the 'discountcode' strings with your real parameter name.
Hope that helps.
Best regards, Chris
Update: added querystring and '?' / '&' handling.
Update 2: changed from prop to attr.
Update 3: changed from 'param' name to 'discountcode'.
Uüdate 4: added length check @ persistedQueryParam and finally got the chance of testing the script :)
Upvotes: 3