jQuery/Javascript - reload current page with an appended querystring?

Viewed 48301

I've got a dropdown menu on my form, which when something is selected I need to reload the current page, but with an appended querystring.

How would I go about doing this?

7 Answers

Actually, there a built-in function of location that you can use, the name of the function is assign.

For appending or modifying there is another built-in function of the URL class that you can use too. the name of the function is searchParams.

So for your case you just need below example:

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

location.assign(url.search);

Update 2022

I create a TypeScript function to apply redirect with params more easier:

const isClient = (): boolean => typeof window !== 'undefined';

type ParamsType = { [key: string]: string | number };

const redirectUrl = (url: string, params?: ParamsType): void => {
  if (isClient()) {
    try {
      const _url = new URL(url);

      if (params) {
        const keyList = Object.keys(params);
        for (let i = 0; i < keyList.length; i += 1) {
          const key = keyList[i];
          _url.searchParams.set(keyList[i], params[key]?.toString());
        }
      }

      window.location.assign(_url.href);
    } catch (e) {
      throw new Error('The URL is not valid');
    }
  }
};

export default redirectUrl;

I was having a requirement to open a particular tab after reloading. So I just needed to append the #tabs-4 to the current url. I know its irrelevant to current post but it could help others who come to this just like I did.

Using the code

window.location = window.location.pathname 
            + window.location.search + '#tabs-4';

did'nt work for me but below code did.

location = "#tabs-4";
location.reload(true);
Related