Javascript: Set cookie - Dynamic URL parameter Name - javascript

I've been strugling looking for a way to set a cookie if a URL parameter is persent. The problem is, the name of the URL parameter is half dynamic.
The URL would be:
http://zzzz.test.bbbb/index.html?transaction[XXXX]=YYYYY
The XXXX is the userID that will change depending on the customer and YYYY is the actual value (transaction number).
I have the following code but it won't recognize the brakets nor what is inside. How can I set it to recognize the URL parameter including the brakets and the dynamic userID within the brakets?
Here is my code:
function URLparam(name) {
return unescape(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
if (URLparam("transaction") !== null && !get_cookie ("Transacion_ID")) {
set_cookie ("Transacion_ID", URLparam("transaction"));
}
if (get_cookie ("Transacion_ID")) {
console.log(get_cookie ("transaction"));
}
});
Any hint would be much appreciated.
Thanks!
NEW ADDITION ==========================
For a link with the following format:
http://zzzz.test.bbbb/index.html?transaction[XXXX][zzzzz]=YYYYY
How would the correct getParameterByName function look like in order to recognize the URL parameter transaction[XXXX][zzzzz] ?
I've tried this but it does not work:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp(name + '(?:\\[\\d+\\]?:\\[\\d+\\])?=' + '(.+?)(&|$)'),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Any ideas?

This version of URLparam() allows an optional [XXX] after the name:
function URLparam(name) {
return unescape(
(RegExp(name + '(?:\\[\\d+\\])?=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
To allow multiple array indexes, change ? (for optional) to * (for any number of repetitions):
function URLparam(name) {
return unescape(
(RegExp(name + '(?:\\[\\d+\\])*=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}

Related

Javascript: Appending second dropdown selection to URL

Hi I have two dropdowns in my webpage. How do I append the second dropdown selection to the URL without using.
window.location.href +="&selected2="+value2;
please tell me what change I must to the the function setsecondparam where value1 is the selection from the first dropdown.
function seturl(sel){
var value = sel.options[sel.selectedIndex].value;
window.location.href = "website.php?selected1="+value;
}
function setsecondparam(sel,value1)
{
var value2 = sel.options[sel.selectedIndex].value;
window.location.href ="website.php?selected1="+value1+"&selected2="+value2;
}
Thanks in advance
It's better to use one function. I wrote it more or less in ES5, you can change it to ES6 if you use babel.
function insertParams (key, value) {
let search = window.location.search;
let regex = new RegExp(key+"=[^\&]*");
search = search.replace(regex, key + '=' + value);
​
if (!regex.test(search)) {
search += (search.length > 0 ? '&' : '?') + key + '=' + value;
}
​
document.location.search = search;
}

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

get only part of current url and redirect with javascript

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

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

is there a way to exclude certain chars from encodeURIComponent

i am building a query string for my url and need to exclude certain chars from the encode.
I want to exclude the "&" and the "=" so that I can make a statement as such:
first=blah&second=blah and so on....
I guess the best way to put it is how do I stop them from being encoded?
some code:
else if (array[i].nodeName == "SELECT") {
if (array[i].id == "multiple") {
var selected = $.map($('#multiple option:selected'),
function (e) {
return $(e).val();
});
$.each(selected, function (index, value) {
name = array[i].name;
values += app + "\&" + key + "=";
});
} else {
name = arr[i].name;
values = arr[i].value;
}
}
key = encodeURIComponent(name);
value = encodeURIComponent(values);
queryString += name + "=" + values + "&";
Is there a way to exclude certain chars from encodeURIComponent?
No. It's a builtin function that takes exactly one argument.
You do need to encode & when it appears in the middle of a key or value so the simplest solution is to encode the individual names and values before combining them. Define
function emit(name, value) {
queryString += (queryString.indexOf("?") >= 0 ? "&" : "?")
+ encodeURIComponent(name) + "=" + encodeURIComponent(value);
}
and then call that function for each name/value pair in multiple selects or once for each other checked input.
else if (array[i].nodeName=="SELECT" ){
if(array[i].id == "multiple"){
var selected = $.map( $('#multiple option:selected'),
function(e){return $(e).val();});
$.each(selected, function(index, value){
emit(array[i].name, value);
});
} else {
emit(arr[i].name, arr[i].value);
}
}
Using encodeURI or similar will not properly encode #, = or other necessary code-points.
The name of the function should suggest how it should be used: call it on the pieces of the query string, not the whole query string.
edit — I've tried to create an example based on your code, but I can't figure out what it's trying to do. As it stands it seems to have syntax errors.

Categories

Resources