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
Related
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.
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'));
}
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.
I need get only this part of current url and redirect after 5 seconds...
example of current url:
http://www.page.com/?archive=filename
i need get only filename and put in javascript code
here my code:
<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script>
<script type="text/javascript">
var country,url;
country = geoip_country_code()
if(country=="US"){
url="http://www.page.com/1.php?archive=filename";
} else if (country == "UK") {
url="http://www.page.com/2.php?archive=filename";
} else if (country == "ES") {
url="http://www.page.com/3.php?archive=filename";
}
setTimeout("location.href = url;",5000);
</script>
please i need help with this code, thanks.
you can use the code posted here:
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 country,
url,
codemap = {
US: 1,
UK: 2,
ES: 3
};
url = "http://www.page.com/" + codemap[geoip_country_code()] + ".php?archive=" + getParameterByName('archive');
setTimeout(function () { location.href = url; },5000);
Here's a previous question on parsing query strings in JavaScript. That one's already marked as a duplicate, so there's undoubtedly more info out there. If this doesn't help, the keywords you want to search for are "Parse query string in JavaScript".
Parse query string in JavaScript
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