append url parameter if exists or add if not exists jQuery - javascript

I am creating a filter based on size, color etc. So it is possible to select multiple items. When I click each item it should append to current URL. Please check the below URL,
If parameter not exists in URL
http://example.com/category-3?tracker=Q2F0ZWdvcnkgMw&color=White
If parameter exists and selected same color
http://example.com/category-3?tracker=Q2F0ZWdvcnkgMw&color=White
If parameter exists and selected multiple colors
http://example.com/category-3?tracker=Q2F0ZWdvcnkgMw&color=White-Black
How to implement the same using jQuery. I have tried using below code,
function setGetParameter(paramName, paramValue) {
var url = window.location.href;
var hash = location.hash;
url = url.replace(hash, '');
if (url.indexOf(paramName + "=") >= 0) {
var prefix = url.substring(0, url.indexOf(paramName + "="));
var suffix = url.substring(url.indexOf(paramName + "="));
suffix = suffix.substring(suffix.indexOf("=") + 1);
suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
url = prefix + paramName + "=" + paramValue + suffix + "-";
} else {
if (url.indexOf("?") < 0)
url += "?" + paramName + "=" + paramValue + "-";
else
url += "&" + paramName + "=" + paramValue + "-";
}
window.location.href = url + hash;
}
The above code works with single parameter value. For multiple values how to alter the above code.

I recommend not using this code at all to build a URL.
Use something like https://medialize.github.io/URI.js/ which happen to have a jQuery plugin.
Why?
Your query parameters here are not encoded, so it could "break" the url. Using a library such as URI.js with a builder to append your query parameters will tackle your issues. Parsing and building URLs is not as trivial as it may seem, so it is better to rely on tested code.
var url = URI(window.location.href); // no need to remove and add the hash back anymore
var queryMap = url.query(true);
if (queryMap[paramName]) {
// param already exists
var values = queryMap[paramName].split('-');
if (!values.includes(paramValue)) {
// paramValue not found: add it
values.push(paramValue);
url.setQuery(paramName, values.join('-'));
}
} else {
// param does not exist yet
url.setQuery(paramName, paramValue);
}
window.location.href = url.toString();

Related

How do I check to see if a field has a value before executing document.getElementById?

This probably isn't very complicated but I'm not a coder by trade so I'm sure I am missing something here.
Here is what I have so far.
function buildURL (){
url = document.getElementById("url").value;
source = document.getElementById("source").value; //required
campaignId = '-_-' + document.getElementById("campid").value; //required
brand = '-_-' + document.getElementById("brand").value; //required
brand2 = '-' + document.getElementById("brand2").value; //optional
brand3 = '-' + document.getElementById("brand3").value; //optional
medium = '-_-' + document.getElementById("medium").value; //required
product = '&cm_mmca1=" + document.getElementById("product").value; //optional
if (url.includes('?')) {
url = url + '&cm_mcc=';
} else {
url = url + '?cm_mmc=';
}
document.getElementById("fullURL").innerHTML = "URL: " + url + source + campaignId + brand + brand2 + brand3 + medium + product ;
}
Now, the url part works great. It prints to screen as soon as I enter a URL in a text box in a form I created and it updates as I make changes. The problem comes with the additional values I print to screen. Everything that proceeds each variable's document.getElementById prints to the screen immediately. This is fine for the required variables but not the optional variables. I'm thinking the solution is to prevent all fields from being passed to document.getElementById("fullURL").innerHTML unless there is a value in the field but I am not sure how to do that. Suggestions?
You need to check each of the option values, and if the value is not an empty String, assign a special value to the variable, else just return an empty String, having no effect on the concatenated final URL:
function buildURL() {
url = document.getElementById("url").value;
source = document.getElementById("source").value; //required
campaignId = '-_-' + document.getElementById("campid").value; //required
brand = '-_-' + document.getElementById("brand").value; //required
medium = '-_-' + document.getElementById("medium").value; //required
// OPTIONAL VALUES: (Use trim() to ensure no white spaces affect our checks)
const brand2Value = document.getElementById("brand2").value.trim();
// ( brand2Value ) ? essentially works much like ( brand2Value !== "" ) ?
brand2 = brand2Value ? '-' + brand2Value : ""; //optional
const brand3Value = document.getElementById("brand3").value.trim();
brand3 = brand3Value ? '-' + brand3Value : ""; //optional
const productValue = document.getElementById("product").value.trim();
product = productValue ? '&cm_mmca1=' + productValue : ""; //optional
if (url.includes('?')) {
url = url + '&cm_mcc=';
} else {
url = url + '?cm_mmc=';
}
document.getElementById("fullURL").innerHTML = "URL: " + url + source + campaignId + brand + brand2 + brand3 + medium + product;
}
Additional notes:
Is there a reason why the function variables (url,source,brand,etc.) are not being declared with var/let/const?
Make sure you always declare variables with either let or const,
otherwise they will become available in the global scope, which is
something we try to avoid in JavaScript.

How to update internal links parameters based on current URL using jQuery?

How we can update the internal links of the page if some visits from specific URL.
For Example.
Some Users comes from Facebook and URL is
https://www.example.com/?utm_source=facebook&utm_medium=cpc&utm_campaign=mobile
and I want to update all my particular links to update based on URL, In case of facebook
Original URL
https://www.example.com/cat/i?pid=ABCD&affid=aff1&affExtParam1=para1&affExtParam2=para2
Updated URL after User visit from facebook link
https://www.example.com/cat/i?pid=ABCD&affid=aff1&affExtParam1=facebook&affExtParam2=mobile
Even If It can edit one parameter in URL that will be helpful.
Note:
In param1 and param2 can be any text in exiting page.
Thanks for the hints. I have tried and able to replace one URL Parameters. Below is the code.
Combined scripts from different answers and use below code.
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|#|$)", "i");
if( value === undefined ) {
if (uri.match(re)) {
return uri.replace(re, '$1$2');
} else {
return uri;
}
} else {
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
} else {
var hash = '';
if( uri.indexOf('#') !== -1 ){
hash = uri.replace(/.*#/, '#');
uri = uri.replace(/#.*/, '');
}
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
return uri + separator + key + "=" + value + hash;
}
}
}
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return decodeURI(results[1]) || 0;
}
}
var key = "affExtParam2";
var value = $.urlParam('utm_source');
$('a').each(function(){
var uri = $(this).attr("href");
$(this).attr("href" , updateQueryStringParameter( uri, key, value ));
});
Not able to test in JS fiddle but working correctly in local, if you guys can further optimize that will be great help.

How to edit this function and make it set URL parameter if it doesn't exist

The following function is designed to replace a variable in the URL.
It works, but I want to make it so that if you pass in a variable that doesn't exist in the URL, it will add it to the URL.
window.setUrlParameter = function(param, value) {
const regExp = new RegExp(param + "(.+?)(&|$)", "g");
const newUrl = window.location.href.replace(regExp, param + "=" + value + "$2");
window.history.pushState("", "", newUrl);
}
There is the function. It takes the param name that you want to replace, and the value you want to set.
As I stated earlier, I want it to be able to not only replace variables, but set them as well.
Thanks!
This function should also be faster than using a regex, modified from this answer.
(The arrow function is just ES6 syntax, you can use normal functions if you want too)
window.setUrlParameter = (param, value) => {
var url = window.location.href;
var hash = location.hash;
url = url.replace(hash, '');
if (url.indexOf(param + "=") >= 0)
{
var prefix = url.substring(0, url.indexOf(param));
var suffix = url.substring(url.indexOf(param));
suffix = suffix.substring(suffix.indexOf("=") + 1);
suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
url = prefix + param + "=" + value + suffix;
}
else
{
if (url.indexOf("?") < 0)
url += "?" + param + "=" + value;
else
url += "&" + param + "=" + value;
}
window.history.pushState(null, null, url + hash);
}
You have the regex, you can just test the url for the same thing, and add it if it isn't there
window.setUrlParameter = function(param, value) {
const regex = new RegExp(param + "(.+?)(&|$)", "g");
const exist = regex.test(window.location.href);
let addQS = window.location.search.length > 0 : '&' : '?';
let newUrl;
if (exist) {
newUrl = window.location.href.replace(regExp, param + "=" + value + "$2");
} else {
newUrl = window.location.href + addQS + param + "=" + value;
}
window.history.pushState("", "", newUrl);
}
I'd highly recommend cleaning this up with RegEx, but you could just check whether or not the href includes the parameter
window.setUrlParameter = function(param, value) {
const regExp = new RegExp(param + "(.+?)(&|$)", "g");
let newUrl = window.location.href.replace(regExp, param + "=" + value + "$2");
if (! window.location.href.includes(param) )
newUrl+='&'+param+'='+value
window.history.pushState("", "", newUrl);
}
Nobody here used the URLSearchParams API, so I thought I'd show you that way:
function modifyLocation( param, value )
{
var qParams = window.location.search.split('?')[0];
var urlParams = new URLSearchParams(qParams);
if( urlParams.has(param) ){
urlParams.delete(param);
}
urlParams.append(param, value);
return window.location.href.split('?')[0] + '?' + urlParams.toString();
}
// To test on CodePen, I used editors = 4, because CodePen has that param
var newUrl = modifyLocation('editors','4');
console.log(newUrl);
// window.history.pushState("", "", newUrl);

Does my simple javascript function, is the best way to add parameters to current URL

I wrote a javascript function that you can use to add parameters to your current URL. It returns your current URL with added parameters. I am not sure if this function will work on all browsers. Currently it works in my Chrome browser perfectly. Can you please tell me disadvantages of this function or how can I improve it or any other way to do the same thing?
function AddParamToURL(param_key, param_value)
{
var currentURL, flag, newURL;
currentURL = window.location.href;
flag = currentURL.indexOf("?");
if (flag == -1)
{
newURL = currentURL + "?" + param_key + "=" + param_value;
}
else
{
newURL = currentURL + param_key + "=" + param_value;
}
return newURL;
}
I would send the path as a parameter to the function, because you won't always be just using the current window.href, you might want to send some other path as well.
You can then remove some redundancy by dealing with the param separator before adding to the path.
And this will work in a loop when you have more than one parameter to add.
function AddParamToURL(currentPath, param_key, param_value)
{
var flag = currentPath.split("?");
var paramSeparator = (flag.length <= 1) ? "?" : "&";
return currentPath + paramSeparator + param_key + "=" + param_value;
}
Fixed the case where there could be a ? without any key after it and added & in second case
Fiddle : http://jsfiddle.net/0spsjeaL/3/
function AddParamToURL(param_key, param_value)
{
var currentURL, flag, newURL;
currentURL = window.location.href;
flag = currentURL.split("?");
if(flag.length <= 1)
{
newURL = currentURL + "?" + param_key + "=" + param_value;
}
else
{
newURL = currentURL + "&" + param_key + "=" + param_value;
}
return newURL;
}
alert(AddParamToURL('name', 'John'));
You can inline a lot of stuff and param_key + "=" + param_value is duplicate code. Also you are forgetting & between parameters.
function AddParamToURL(param_key, param_value)
{
var url = window.location.href;
var newUrl = url.indexOf('?') < 0 ? url + '?' : url + '&';
return newUrl + param_key + '=' param_value;
}

Add / Change parameter of URL and redirect to the new URL

If the &view-all parameter does NOT exist in the URL I need to add it to the end of the URL along with a value. If it DOES exist then I need to be able to just change the value without creating a new URL because it might, or might not, have other parameters before it.
I found this function but I can't get it to work: https://stackoverflow.com/a/10997390/837705
Here is the code I have using the function above (which I can't get to work): http://jsfiddle.net/Draven/tTPYL/4/
I know how to append the parameter and value already:
<div onclick="javascript: window.location.assign(window.location.href+='&view-all=Yes');">Blah Blah</div>
More Info:
If the URL is http://www.domain.com/index.php?action=my_action then the default "&view-all" value would be "Yes" so the URL they would be directed to when they click the button is http://www.domain.com/index.php?action=my_action&view-all=Yes.
If the URL is http://www.domain.com/index.php?action=my_action&view-all=Yes then when they click the button it would change to http://www.domain.com/index.php?action=my_action&view-all=No​​​
EDIT: Please give me examples. I don't know alot of JS, and I just can't think of a way to do it in PHP.
function setGetParameter(paramName, paramValue)
{
var url = window.location.href;
var hash = location.hash;
url = url.replace(hash, '');
if (url.indexOf(paramName + "=") >= 0)
{
var prefix = url.substring(0, url.indexOf(paramName + "="));
var suffix = url.substring(url.indexOf(paramName + "="));
suffix = suffix.substring(suffix.indexOf("=") + 1);
suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
url = prefix + paramName + "=" + paramValue + suffix;
}
else
{
if (url.indexOf("?") < 0)
url += "?" + paramName + "=" + paramValue;
else
url += "&" + paramName + "=" + paramValue;
}
window.location.href = url + hash;
}
Call the function above in your onclick event.
Why parse the query string yourself when you can let the browser do it for you?
function changeQS(key, value) {
let urlParams = new URLSearchParams(location.search.substr(1));
urlParams.set(key, value);
location.search = urlParams.toString();
}
All the preivous solution doesn't take in account posibility of the substring in parameter. For example http://xyz?ca=1&a=2 wouldn't select parameter a but ca. Here is function which goes through parameters and checks them.
function setGetParameter(paramName, paramValue)
{
var url = window.location.href;
var hash = location.hash;
url = url.replace(hash, '');
if (url.indexOf("?") >= 0)
{
var params = url.substring(url.indexOf("?") + 1).split("&");
var paramFound = false;
params.forEach(function(param, index) {
var p = param.split("=");
if (p[0] == paramName) {
params[index] = paramName + "=" + paramValue;
paramFound = true;
}
});
if (!paramFound) params.push(paramName + "=" + paramValue);
url = url.substring(0, url.indexOf("?")+1) + params.join("&");
}
else
url += "?" + paramName + "=" + paramValue;
window.location.href = url + hash;
}
I had a similar situation where I wanted to replace a URL query parameter. However, I only had one param, and I could simply replace it:
window.location.search = '?filter=' + my_filter_value
The location.search property allows you to get or set the query portion of a URL.
To do it in PHP: You have a couple of parameters to view your page, lets say action and view-all. You will (probably) access these already with $action = $_GET['action'] or whatever, maybe setting a default value.
Then you decide depending on that if you want to swich a variable like $viewAll = $viewAll == 'Yes' ? 'No' : 'Yes'.
And in the end you just build the url with these values again like
$clickUrl = $_SERVER['PHP_SELF'] . '?action=' . $action . '&view-all=' . $viewAll;
And thats it.
So you depend on the page status and not the users url (because maybe you decide later that $viewAll is Yes as default or whatever).
Some simple ideas to get you going:
In PHP you can do it like this:
if (!array_key_exists(explode('=', explode('&', $_GET))) {
/* add the view-all bit here */
}
In javascript:
if(!location.search.match(/view\-all=/)) {
location.href = location.href + '&view-all=Yes';
}
though i take the url from an input, it's easy adjustable to the real url.
var value = 0;
$('#check').click(function()
{
var originalURL = $('#test').val();
var exists = originalURL.indexOf('&view-all');
if(exists === -1)
{
$('#test').val(originalURL + '&view-all=value' + value++);
}
else
{
$('#test').val(originalURL.substr(0, exists + 15) + value++);
}
});
http://jsfiddle.net/8YPh9/31/
Here's a way of accomplishing this. It takes the param name and param value, and an optional 'clear'. If you supply clear=true, it will remove all other params and just leave the newly added one - in other cases, it will either replace the original with the new, or add it if it's not present in the querystring.
This is modified from the original top answer as that one broke if it replaced anything but the last value. This will work for any value, and preserve the existing order.
function setGetParameter(paramName, paramValue, clear)
{
clear = typeof clear !== 'undefined' ? clear : false;
var url = window.location.href;
var queryString = location.search.substring(1);
var newQueryString = "";
if (clear)
{
newQueryString = paramName + "=" + paramValue;
}
else if (url.indexOf(paramName + "=") >= 0)
{
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var keyValues = queryString.split('&');
for(var i in keyValues) {
var key = keyValues[i].split('=');
if (key.length > 1) {
if(newQueryString.length > 0) {newQueryString += "&";}
if(decode(key[0]) == paramName)
{
newQueryString += key[0] + "=" + encodeURIComponent(paramValue);;
}
else
{
newQueryString += key[0] + "=" + key[1];
}
}
}
}
else
{
if (url.indexOf("?") < 0)
newQueryString = "?" + paramName + "=" + paramValue;
else
newQueryString = queryString + "&" + paramName + "=" + paramValue;
}
window.location.href = window.location.href.split('?')[0] + "?" + newQueryString;
}
i would suggest a little change to #Lajos's answer... in my particular situation i could potentially have a hash as part of the url, which will cause problems for parsing the parameter that we're inserting with this method after the redirect.
function setGetParameter(paramName, paramValue) {
var url = window.location.href.replace(window.location.hash, '');
if (url.indexOf(paramName + "=") >= 0) {
var prefix = url.substring(0, url.indexOf(paramName));
var suffix = url.substring(url.indexOf(paramName));
suffix = suffix.substring(suffix.indexOf("=") + 1);
suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
url = prefix + paramName + "=" + paramValue + suffix;
}else {
if (url.indexOf("?") < 0)
url += "?" + paramName + "=" + paramValue;
else
url += "&" + paramName + "=" + paramValue;
}
url += window.location.hash;
window.location.href = url;
}
This is my sample code for rebuild url query string with JS
//function get current parameters
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
};
//build a new parameters
var param1 = $.urlParam('param1');
var param2 = $.urlParam('param2');
//check and create an array to save parameters
var params = {};
if (param1 != null) {
params['param1'] = param1;
}
if (order != null) {
params['param2'] = param2;
}
//build a new url with new parameters using jQuery param
window.location.href = window.location.origin + window.location.pathname + '?' + $.param(params);
I used JQUERY param: http://api.jquery.com/jquery.param/ to create a new url with new parameters.
I need help to adjust my script below or to find a script that could be used on my wordpress site to grab the url suffix parameters from a forward url, then to be added at the button click url for tracking the proper forward ads id.
REASON: parameters are used for advertisement tracking to find out from which ad the user has been forward, even if the user hops from optin page to the sales page by using button click.
Here the goal to reach:
1. An FB ad points to an optin page with tracking code: https://ownsite.com/optin-page/?tid=fbad1
2. At the optin-page there is a button with a setup URL to forward to the sales page, but if clicked then only the URL is forward, but the parameter "?tid=fbad1" is missing.
3. The auto-forward script below (which is working properly) can be used to change for button click forward, but has a limitation as it grab only "tid" parameters instead also utm parameters.
Therefore a script code shall be implemented to establish click buttons (also to style them or use images instead) and while clicking the button to forward to a different sales page with grabbing the suffix parameter form the current optin-page to forward then to sales-page https://ownsite.com/sales-page/?tid=fbad1 also including UTM parameters
Currently, I could have solved this by using an auto-redirect script, but
A.) I do not want to use an autoredirect at this page. Better is an event click button used to let the user himself click to forward with the URL parameter included.
B.) The tracking ID parameter in this script is limited to "?tid=..." instead I do also want to track the UTM code on button click also
i.e. Grab from current page the paramater of URL https://www.optin-page.com/?tid=facebookad1?utm_campaign=blogpost then on button click grab parameters and add to button set URL https://www.sales-page.com/?tid=facebookad1?utm_campaign=blogpost
Please now find here the Code below in use for auto-redirect and grabbing the URL parameters. This code shall be changed now to be able to create a button with a click-event to be redirect then to the forward URL with parameter grabbing of current URL if the button is clicked (as stated above).
<p><!-- Modify this according to your requirement - core script from https://gist.github.com/Joel-James/62d98e8cb3a1b6b05102 and suffix grabbing </p>
<h3 style="text-align: center;"><span style="color: #ffffff; background-color: #039e00;">►Auto-redirecting after <span id="countdown">35</span> seconds◄</span></h3>
<p><!-- JavaScript part --><br /><script type="text/javascript">
function findGetParameter(parameterName) {
var result = null,
tmp = [];
location.search
.substr(1)
.split("&")
.forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
});
return result;
}
// Total seconds to wait
var seconds = 45;
function countdown() {
seconds = seconds - 1;
if (seconds < 0) {
// Chnage your redirection link here
var tid = findGetParameter('tid');
window.location = "https://www.2share.info/ql-cb2/" + '?tid='+tid;
} else {
// Update remaining seconds
document.getElementById("countdown").innerHTML = seconds;
// Count down using javascript
window.setTimeout("countdown()", 1000);
}
}
// Run countdown function
countdown();
</script></p>
var updateQueryStringParameter = function (key, value) {
var baseUrl = [location.protocol, '//', location.host, location.pathname].join(''),
urlQueryString = document.location.search,
newParam = key + '=' + value,
params = '?' + newParam;
// If the "search" string exists, then build params from it
if (urlQueryString) {
var updateRegex = new RegExp('([\?&])' + key + '[^&]*');
var removeRegex = new RegExp('([\?&])' + key + '=[^&;]+[&;]?');
if( typeof value == 'undefined' || value == null || value == '' ) {
params = urlQueryString.replace(removeRegex, "$1");
params = params.replace( /[&;]$/, "" );
} else if (urlQueryString.match(updateRegex) !== null) {
params = urlQueryString.replace(updateRegex, "$1" + newParam);
} else {
params = urlQueryString + '&' + newParam;
}
}
// no parameter was set so we don't need the question mark
params = params == '?' ? '' : params;
window.history.replaceState({}, "", baseUrl + params);
};
I think something like this would work, upgrading the #Marc code:
//view-all parameter does NOT exist
$params = $_GET;
if(!isset($_GET['view-all'])){
//Adding view-all parameter
$params['view-all'] = 'Yes';
}
else{
//view-all parameter does exist!
$params['view-all'] = ($params['view-all'] == 'Yes' ? 'No' : 'Yes');
}
$new_url = $_SERVER['PHP_SELF'].'?'.http_build_query($params);

Categories

Resources