[javascript] append to url and refresh page

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?

This question is related to javascript jquery refresh

The answer is


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;

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).


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

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

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

Change:

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

To:

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


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

Also:

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

Just one liner of Shlomi answer usable in bookmarklets


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;

Try this

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

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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to refresh

How to Refresh a Component in Angular Angular + Material - How to refresh a data source (mat-table) How to Update a Component without refreshing full page - Angular How to reload page the page with pagination in Angular 2? Swift: Reload a View Controller Button that refreshes the page on click Update data on a page without refreshing How to refresh or show immediately in datagridview after inserting? Gradle project refresh failed after Android Studio update Refresh Part of Page (div)