Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set querystring with Javascript

Tags:

javascript

Is there a way to set the values of a querystring using javascript?

My page has a filter list that when clicked, it will alter the in-page results pane on the right hand side.

I'm trying to update to the querystring values of the url, so if the user leaves the page, then clicks the "back" buttons they'll be return to the last filter selection set.

For example:
Landing: foo.html
Click 1: foo.html?facets=bar
Click 2: foo.html?facets=bar|baz
Click 3: foo.html?facets=bar|baz|zap

Is this possible?

like image 735
rsturim Avatar asked Apr 05 '11 01:04

rsturim


3 Answers

It is possible, but it will refresh the page.

document.location = "?facets=bar";

If you don't care about browser support, you can use the HTML5 history.pushState.

like image 173
Peter Olson Avatar answered Oct 23 '22 06:10

Peter Olson


const params = new URLSearchParams(location.search);
params.set('test', 123);
params.set('cheese', 'yummy');

params.toString(); // => test=123&cheese=yummy
window.history.replaceState({}, '', `${location.pathname}?${params.toString()}`);
like image 41
Dryden Williams Avatar answered Oct 23 '22 06:10

Dryden Williams


You can use Javascript to change the hash (the #hash-part of the URL), but changing the query string means you have to reload the page. So, no, what you want to do is not possible in that way.

An alternative is to use Javascript to change the hash, then check the hash on page load to change your results dynamically. You're looking for something like jQuery Address.

like image 4
Kelly Avatar answered Oct 23 '22 07:10

Kelly