Append to URL and refresh page

JavascriptJqueryRefresh

Javascript Problem Overview


I am looking to write a piece of javascript that will append a parameter to the current URL and then refresh the page - how can I do this?

Javascript Solutions


Solution 1 - Javascript

this should work (not tested!)

var url = window.location.href;    
if (url.indexOf('?') > -1){
   url += '&param=1'
}else{
   url += '?param=1'
}
window.location.href = url;

Solution 2 - Javascript

Shorter than the accepted answer, doing the same, but keeping it simple:

window.location.search += '&param=42';

We don't have to alter the entire url, just the query string, known as the search attribute of location.

When you are assigning a value to the search attribute, the question mark is automatically inserted by the browser and the page is reloaded.

Solution 3 - Javascript

Most of the answers here suggest that one should append the parameter(s) to the URL, something like the following snippet or a similar variation:

location.href = location.href + "&parameter=" + value;

This will work quite well for the majority of the cases.

However

That's not the correct way to append a parameter to a URL in my opinion.

Because the suggested approach does not test if the parameter is already set in the URL, if not careful one may end up with a very long URL with the same parameter repeated multiple times. ie:

https://stackoverflow.com/?&param=1&param=1&param=1&param=1&param=1&param=1&param=1&param=1&param=1

at this point is where problems begin. The suggested approach could and will create a very long URL after multiple page refreshes, thus making the URL invalid. Follow this link for more information about long URL https://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers

This is my suggested approach:

function URL_add_parameter(url, param, value){
	var hash       = {};
	var parser     = document.createElement('a');
	
	parser.href    = url;

	var parameters = parser.search.split(/\?|&/);

	for(var i=0; i < parameters.length; i++) {
		if(!parameters[i])
			continue;

		var ary      = parameters[i].split('=');
		hash[ary[0]] = ary[1];
	}

	hash[param] = value;

	var list = [];	
	Object.keys(hash).forEach(function (key) {
		list.push(key + '=' + hash[key]);
	});

	parser.search = '?' + list.join('&');
	return parser.href;
}

With this function one just will have to do the following:

location.href = URL_add_parameter(location.href, 'param', 'value');

Solution 4 - Javascript

If you are developing for a modern browser, Instead of parsing the url parameters yourself- you can use the built in URL functions to do it for you like this:

const parser = new URL(url || window.location);
parser.searchParams.set(key, value);
window.location = parser.href;

Solution 5 - Javascript

location.href = location.href + "&parameter=" + value;

Solution 6 - Javascript

This line of JS code takes the link without params (ie before '?') and then append params to it.

window.location.href = (window.location.href.split('?')[0]) + "?p1=ABC&p2=XYZ";

The above line of code is appending two params p1 and p2 with respective values 'ABC' and 'XYZ' (for better understanding).

Solution 7 - Javascript

function gotoItem( item ){
    var url = window.location.href;
    var separator = (url.indexOf('?') > -1) ? "&" : "?";
    var qs = "item=" + encodeURIComponent(item);
    window.location.href = url + separator + qs;
}

More compat version

function gotoItem( item ){
    var url = window.location.href;    
    url += (url.indexOf('?') > -1)?"&":"?" + "item=" + encodeURIComponent(item);
    window.location.href = url;
}

Solution 8 - Javascript

Please check the below code :

/*Get current URL*/    
var _url = location.href; 
/*Check if the url already contains ?, if yes append the parameter, else add the parameter*/
_url = ( _url.indexOf('?') !== -1 ) ? _url+'&param='+value : _url+'?param='+value;
/*reload the page */
window.location.href = _url;

Solution 9 - Javascript

One small bug fix for @yeyo's thoughtful answer above.

Change:

var parameters = parser.search.split(/\?|&/);

To:

var parameters = parser.search.split(/\?|&amp;/);

Solution 10 - Javascript

Try this

var url = ApiUrl(`/customers`);
  if(data){
   url += '?search='+data; 
  }
  else
  { 
      url +=  `?page=${page}&per_page=${perpage}`;
  }
  console.log(url);

Solution 11 - Javascript

Also:

window.location.href += (window.location.href.indexOf('?') > -1 ? '&' : '?') + 'param=1'

Just one liner of Shlomi answer usable in bookmarklets

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionamateurView Question on Stackoverflow
Solution 1 - JavascriptShlomi KomemiView Answer on Stackoverflow
Solution 2 - JavascriptBo FrederiksenView Answer on Stackoverflow
Solution 3 - JavascriptyeyoView Answer on Stackoverflow
Solution 4 - JavascriptKadeView Answer on Stackoverflow
Solution 5 - JavascriptPaul AlexanderView Answer on Stackoverflow
Solution 6 - JavascriptAnmolView Answer on Stackoverflow
Solution 7 - JavascriptepascarelloView Answer on Stackoverflow
Solution 8 - JavascriptAftabView Answer on Stackoverflow
Solution 9 - JavascriptGabrienView Answer on Stackoverflow
Solution 10 - JavascriptAtchutha rama reddy KarriView Answer on Stackoverflow
Solution 11 - JavascriptestaniView Answer on Stackoverflow