Using Cookies to Capture UTM URL Parameters - javascript

I read the following post to understand how to use cookies to capture UTM URL Parameters:
https://jennamolby.com/how-to-use-cookies-to-capture-url-parameters/
I genuinely think that the code she outlined has all the write steps, but that it wont actually work. Getting this in Stackoverflow so that we can update the code and so that we can update the author so that others (like myself) do not have issues going forward.
Parse the URL
The URL parameters need to be parsed so the cookie values can be set. This can be done using javascript.
// Parse the URL
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
// Give the URL parameters variable names
var source = getParameterByName('utm_source');
var medium = getParameterByName('utm_medium');
var campaign = getParameterByName('utm_campaign');
Setting the Cookie Values
In order to set the cookie values, jQuery and the jQuery Cookie Plugin must be on the page.
<script src="https://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="/path/to/js.cookie.js"></script>
Using the variables defined in the first step, the cookie values can be set.
// Set the cookies
if($.cookie('utm_source') == null || $.cookie('utm_source') == "") {
$.cookie('utm_source', source);
}
if($.cookie('utm_medium') == null || $.cookie('utm_medium') == "") {
$.cookie('utm_medium', medium);
}
if($.cookie('utm_campaign') == null || $.cookie('utm_campaign') == "") {
$.cookie('utm_campaign', campaign);
}
Then we grab the cookie values and set the form field values
// Grab the cookie value and set the form field values
$(document).ready(function(){
$('input[name=utm_source').val(utm_source);
$('input[name=utm_medium').val(utm_medium);
$('input[name=utm_campaign').val(utm_campaign);
});
I have the following questions:
Does Jquery still support cookies?
I am confused about the below code. I do not think this will work, because it is not reading the cookie values.
// Grab the cookie value and set the form field values
$(document).ready(function(){
$('input[name=utm_source').val(utm_source);
$('input[name=utm_medium').val(utm_medium);
$('input[name=utm_campaign').val(utm_campaign);
});
Shouldn't the code be the following:
$(document).ready(function(){
/ Put the variable names into the hidden fields in the form.
$('input[name=utm_source]').val($.cookie('utm_source'));
$('input[name=utm_medium]').val($.cookie('utm_medium')_;
$('input[name=utm_campaign]').val($.cookie('utm_campaign'));
}

Related

Storing parsed URL in Cookie (not storing the entire value)

TL;DR: I am forced to use a javascript solution to store a URL parameter as a cookie, but when the function runs, it only stores the first 5 characters of the value I need.
I am working on implementing affiliate sales tracking across domains. As stated above, I need to store a value from a URL in a cookie so that I can pull it into a separate (functioning) script later. On my primary domain, I was able to do this with a simple .php script, but the third-party platform we use for our sales doesn't allow me to run .php scripts, so I found a javascript function that seemed to be working prior to today. That said, prior to today I was using test parameters that were only numerical (1234567890, etc.).
Here is an example of the kind of URL and parameter being used:
https://subdomain.platform-domain.com/subscribe/Product_ID?irclickid=QW6QnmxpdxySWmnwUx0Mo6bwUkEx5HXJxUUm0c0
This is the function I've been using successfully up until now:
function getParameterByName(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'),
results = regex.exec(location.search);
return results === null
? ''
: decodeURIComponent(results[1].replace(/\+/g, ' '));
}
var results = getParameterByName('irclickid');
if (results != null || results != '') {
Cookies.set('irclickid', results, { expires: 30 });
}
For some reason, the function now only stores the first 5 characters of the value, or "QW6Qn" in this case. Any help or direction on how to make this work correctly is appreciated.
Resolution:
I found a function that was more apt for what I needed here on stackoverflow: How to get parameter name?, and replaced the first part of my javascript with the following, and it is now working as expected!
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
The last section remained the same:
var results = getParameterByName('irclickid');
if (results != null || results != '') {
Cookies.set('irclickid', results, { expires: 30 });
}
Thank you to those that offered help and insight.
const url = new URL('https://subdomain.platform-domain.com/subscribe/Product_ID?irclickid=QW6QnmxpdxySWmnwUx0Mo6bwUkEx5HXJxUUm0c0')
document.cookie = `irclickid=${url.searchParams.get('irclickid')}; expires=...`
You can see on https://caniuse.com/url if all required browsers support URL.

how to check for empty "//" slashes in a input field

I want to check whether a regex field is empty or not and depending on that I want to execute a function.
the input field is a regex field and by default it stores "//" value in the field and I dont want to execute a function if the value contains "//" . Only when user enters some value I would wnat to execute the function.
new shared.form.RegexField({
ref : 'regexField',
fieldLabel : 'Regular Expression',
allowBlank : false,
width : 300,
});
Ex:
var rule = "//";
if(rule) {
// dont do anything;
}
however if rule contains some value like:
rule = "/test/";
if(rule) {
// call API sevrice.
}
is this possible?
if (rule.match("/\/\//")) {
// don't call because it's equal to "//"
} else {
// call API service
}
var rule = '//www.example.com'
if(rule.replace(/(\/\/)(?=(\S)*)/,'')){
// call API sevrice.
}else {
// dont do anything;
}

JavaScript Cookie - Form not passing the utm_source value

I'm using the JavaScript to create a cookie that will post the utm_source value="".
On the console I see the utm_source value, but not on the form
// Parse the URL
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
// Give the URL parameters variable names
var source = getParameterByName('utm_source');
// Set the cookies
if(Cookies.set('utm_source') == null || Cookies.set('utm_source') == "") {
Cookies.set('utm_source', source);
}
// Grab the cookie value and set the form field values
$(document).ready(function(){
$('input[name=utm_source').val(utm_source);
});
</script>
Problem 1
$('input[name=utm_source').val(utm_source);
The above line is causing problems for two reasons:
You're missing a closing bracket
utm_source is not defined anywhere (in the snippet you posted)
If you want to use the cookie value, you should do this:
$('input[name=utm_source]').val(Cookies.get('utm_source'));
Problem 2
On this line:
if(Cookies.set('utm_source') == null || Cookies.set('utm_source') == "") {
I think that you're mistakenly using .set() instead of .get() and that it could be simplified into this:
if(!Cookies.get('utm_source')) {
which would work because null and "" are both falsy values.
Thank you guys! Got it to work! Had to replace the name=customID

Javascript URL Query String Logic

I have an events listing page which can be filtered by type and also by date using query string variables.
I am trying to achieve the following logic using javascript/jQuery.
I have a calendar which fires a function when updated. When fired I need to implement the following logic:
If the current URL contains ?filter= then add &dateStart= to the end of the URL.
If the current URL contains ?filter= AND &dateStart= then keep the current filter value but replace the date query string with a new one.
If the current URL contains ONLY ?dateStart= then replace it with the new one.
I have tried various methods to achieve this but I keep hitting the problem of appending information to the end of the URL rather than replacing parts of it.
Any help would be appreciated.
Thanks.
You can try something like this:
NOTE: not tested.
var newDateValue;
var myPath = window.location.pathname
//check if path contains the different variables
var containsFilter = myPath.indexOf("?filter=") != -1 ? true : false;
var containsAppendedDateStart = myPath.indexOf("&dateStart=" != -1 ? true : false;
var containsDateStart = myPath.indexOf("?dateStart=" != -1 ? true : false;
if(containsFilter && !containsAppendedDateStart){
// If the current URL contains ?filter= then add &dateStart= to the end of the URL.
window.location.replace(window.location.href + "&dateStart=");
}else if(containsFilter && containsAppendedDateStart){
//If the current URL contains ?filter= AND &dateStart= then keep the current filter value but replace the date query string with a new one.
newDateValue = 10; // add your new value here
var splittedPathArray = myPath.split("&dateStart=");
var newUrl = window.location.protocol + "//" + window.location.host + "/" + splittedPathArray[0] + "&dateStart=" + addNewValue;
window.location.replace(newUrl);
}else if(containsDateStart){
// If the current URL contains ONLY ?dateStart= then replace it with the new one.
newDateValue = 15;// add your new value here
var splittedPathArray = myPath.split("?dateStart=");
var newUrl = window.location.protocol + "//" + window.location.host + "/" + splittedPathArray[0] + "?dateStart=" + addNewValue;
}
You can achieve this more easy with native Web API or vanilla javascript than with jQuery. As far as jQuery don't provide any specific function to work with query strings.
The new URLSearchParams object provide a few methods to work more easily with URL query strings. In your case for example you'll need to do something like this:
function updateQueryString(queryString, dateStart) {
var queryString = new URLSearchParams(queryString);
queryString.has('dateStart')
? queryString.set('dateStart', dateStart)
: queryString.append('dateStart', dateStart);
return queryString.toString();
}
for this solution you'll need a polyfill
Sadly this is not yet implemented by the majority of web browsers and you'll need to "polyfill" the URLSearchParams object for this solution to work properly. You'll have to add this line to the <head> section in your html:
<script src="https://cdn.rawgit.com/inexorabletash/polyfill/v0.1.14/polyfill.min.js"></script>
You can find more information about the URLSearchParams in the Mozilla Developers Network Documentation, the WHATWG specification for the URL Standard or the specification by the W3C
solution without polyfill
​
If you don't like to use edge features you still can do it without any extra polyfill. It would look like this:
function updateQueryString(queryString, dateStart) {
var qsObject = {};
queryString
.substring(1) // ignore '?'
.split('&').forEach(function (param) {
param = param.split('=');
qsObject[param[0]] = param[1];
});
qsObject['dateStart'] = dateStart;
return '&' + Object.keys(qsObject)
.map(function (key) {
return key + '=' + qsObject[key];
})
.join('?');
}
Call whatever version of the updateQueryString function you rather like this:
updateQueryString(windonw.location.search, dateStart)

script for on load alert box based on url

I am creating a submittal form, sending the form to a php form, and after the form completes having it redirect to the initial page with an additional "?s=1" in the url.
Basically what I am trying to do is create an alert box pop up on loading the page with the "?s=1" in the url.
It is a very brute force method to use I know, but i can't seem to get the small script to work correctly. I know for certain everything works and loads to the point and reloads the initial page with ?s=1 in it.
Here is the code i'm using to try and prompt the alert box
enter code here <script type="text/javascript">
var Path = window.location.href;
if (Path == "mywebsite.html?s=1")
{
alert("Your Form Has Been Submitted.")
}
else()
{
}
</script>
Does anybody know why the box will not appear? Or possibly an alternate method for what I am attempting to do? Thanks.
window.location.href contains the complete URL, including the domain, and the full path, so a basic equality comparison won't work unless you're exaclty matching it, and even still this could cause problems (e.g. www. versus a naked domain, https:// versus http://, etc.). A possible solution is to use RegEx.
var pathRegex = /mywebsite\.html\?s\=1/;
if (pathRegex.test(window.location.href)) {
alert("Your Form Has Been Submitted.")
}
As a note, you can have an if statement without an accompanying else, and else statements don't take any arguments in parentheses like if, unless you're talking about else if.
Here is some code I wrote up for one of my projects that lets you pull a parameter and value out of the url.
function GetURLParameter(urlParameter){
var url = window.location.search.substring(1);
var urlVariables = url.split('&');
for (var i = 0; i < urlVariables.length; i++){
var parameter = urlVariables[i].split('=');
if (parameter[0] == urlParameter){
return parameter[1];
}
}
}
It's easy to use:
For mywebsite.com?s=1
It would just be
var k = GetURLParameter('s');
if (k == 1){
alert("Your Form Has Been Submitted.")
}
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
And then check like...
if (getParameterByName("s")=="1")
{
alert("Your Form Has Been Submitted.")
}
else
{
}

Categories

Resources