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

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.

Related

Using Cookies to Capture UTM URL Parameters

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'));
}

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

Setting a variable with URL

I have deployed a firebase site which works fine. The problem I have is the next:
Inside my main.js I have a variable called company. Is there a way to set that variable depending on the URL? For example:
site-ce207.firebaseapp.com/company=01
Or do you know another way?
As Mouser pointed out, this is invalid:
site-ce207.firebaseapp.com/company=01
However, this isnt:
site-ce207.firebaseapp.com#company=01&id=5
And it can be easily parsed:
var queries=location.hash.slice(1).split("&").map(el=>el.split("="));
Queries now.looks like this:
[
["company","01"],
["id","5"]
]
So to resolve it may do use an object:
var getQuery={};
queries.forEach(query=>getQuery[query[0]]=query[1]);
So now its easy to get a certain key:
console.log(getQuery["company"]);
Or new and more easy using a Map:
var query=new Map(queries);
console.log(query.get("company"));
I have a simple function I found a long time ago to handle this. I modified a bit to get the value by doing this.
function param(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 to use the value I do the following
var myCity = param('cityid');
when issuing something like: http://example.com/?cityid=Guatemala
myCity will have the value of 'Guatemala' in my app.

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
{
}

JQuery Detect If in Homepage and Homepage PLUS url Variables

I am using this code to detect the homepage and it works great:
var url= window.location.href;
if(url.split("/").length>3){
alert('You are in the homepage');
}
My problem is that I also need to detect if the url has variables for example:
mysite.com?variable=something
I need to also detect if the url has variables on it too
How can I do this?
Using window.location.pathname could work too:
if ( window.location.pathname == '/' ){
// Index (home) page
} else {
// Other page
console.log(window.location.pathname);
}
See MDN info on window.location.pathname.
You can find out if you're on the homepage by comparing href to origin:
window.location.origin == window.location.href
To get the query parameters you can use the answer here:
How can I get query string values in JavaScript?
Take a look at the window.location docs , the information you want is in location.search , so a function to check it could just be:
function url_has_vars() {
return location.search != "";
}
if current url is xxxxx.com something like that, then xxx
if (window.location.href.split('/').pop() === "") {
//this is home page
}
You need a query string searching function to do this..
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, " "));
}
Before redirect check the query string and match with the expected value and redirect as requirement.
Taking inspiration from Mataniko suggestion, I slightly modified it to fix its issue:
if (window.location.origin + "/" == window.location.href ) {
// Index (home) page
...
}
In this way, this test pass only in homepage

Categories

Resources