52

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?

Probocop
  • 10,346
  • 28
  • 85
  • 115

7 Answers7

58

This is an old question but it came up first in google search results.

The solution I went with is similar to jAndy's.

window.location.pathname gives me the page's url without the query string. I'm then able to build the query string with "?"+$.param({'foo':'bar','base':'ball'}) which I then append to the pathname and set to window.location.href.

window.location.href = window.location.pathname+"?"+$.param({'foo':'bar','base':'ball'})
Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133
jgreen
  • 1,132
  • 2
  • 14
  • 18
  • 6
    Hi jgreen, welcome to Stack Overflow. Thank you for sharing your solution as another answer. Providing a detailed answer to an old question will certainly help future visitors as well. +1 – jamesmortensen Nov 03 '12 at 00:11
18
var params = [
    "foo=bar",
    "base=ball"
];

window.location.href =
    "http://" +
    window.location.host +
    window.location.pathname +
    '?' + params.join('&');

That code within your change event handler will do the trick.

For instance:

$('#my_dropdown_id').bind('change', function(){
    var params = [
        "foo=bar",
        "base=" + $(this).val()
    ];

    window.location.href = "http://" + window.location.host + window.location.pathname + '?' + params.join('&');
});
Richard Garside
  • 87,839
  • 11
  • 80
  • 93
jAndy
  • 231,737
  • 57
  • 305
  • 359
16

If you go with the top rated answer, you may want to replace

http://

in the code with

window.location.protocol

so that it works for other protocols, like https or file. So

window.location.href = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + params.join('&');
broetchen
  • 449
  • 4
  • 11
6

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;
AmerllicA
  • 29,059
  • 15
  • 130
  • 154
5

If you want a simple way to preserve the query string and possibly append to it, use window.location.search; here's a snippet:

var search = window.location.search + (window.location.search ? "&" : "?");
search += "param1=foo&param2=bar";
window.location.href = window.location.protocol + "//" + window.location.host + window.location.pathname + search;

You can, of course, use a more sophisticated way of building the rest of your query string, as found in the other examples, but the key is to leverage Location.search.

Peppermintology
  • 9,343
  • 3
  • 27
  • 51
Tom Auger
  • 19,421
  • 22
  • 81
  • 104
3

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);
A_01
  • 1,021
  • 11
  • 27
2

If you have an existing querystring that you'd like to keep then this version does that and adds your new params to any existing ones. The keys are converted to lowercase so that duplicates are not added. Maintaining the quersytring does make the solution more complicated, so I'd only do this if you need to.

$("#sortby").change(function () {

    var queryString = getQueryStrings();
    // Add new params to the querystring dictionary
    queryString["sortby"] = $("#sortby").val();

    window.location.href =
        window.location.protocol + "//" +
        window.location.host +
        window.location.pathname +
        createQueryString(queryString);
});


// http://stackoverflow.com/questions/2907482
// Gets Querystring from window.location and converts all keys to lowercase
function getQueryStrings() {
    var assoc = {};
    var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
    var queryString = location.search.substring(1);
    var keyValues = queryString.split('&');

    for (var i in keyValues) {
        var key = keyValues[i].split('=');
        if (key.length > 1) {
            assoc[decode(key[0]).toLowerCase()] = decode(key[1]);
        }
    }

    return assoc;
}

function createQueryString(queryDict) {
    var queryStringBits = [];
    for (var key in queryDict) {
        if (queryDict.hasOwnProperty(key)) {
            queryStringBits.push(key + "=" + queryDict[key]);
        }
    }
    return queryStringBits.length > 0
        ? "?" + queryStringBits.join("&")
        : "";
}
Richard Garside
  • 87,839
  • 11
  • 80
  • 93