Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending parameter to URL without refresh

I know this has been asked many times before but answers were not descriptive enough to solve my problem. I don't want to change the whole URL of page. I want to append a parameter &item=brand on button click without refresh.

Using document.location.search += '&item=brand'; makes the page refresh.

Using window.location.hash = "&item=brand"; append without refresh but with a hash # which eliminates the usage/effect of the parameter. I tried to remove the hash after appending but that didn't work.


This answer and many others suggest the use of HTML5 History API, specifically the history.pushState method, and for old browsers is to set a fragment identifier to prevent page from reloading. But how?


Assuming the URL is: http://example.com/search.php?lang=en

How can I append &item=brand using HTML5 pushState method or a fragment identifier so the output would be like this: http://example.com/search.php?lang=en&item=brand without a page refresh?


I hope someone can throw some light on how to use the HTML5 pushState to append a parameter to an existing/current URL. Or alternatively how to set a fragment identifier for the same purpose. A good tutorial, demo or piece of code with a little explanation would be great.

Demo of what I've done so far. Your answers would be greatly appreciated.

like image 214
Mina Hafzalla Avatar asked Sep 28 '15 16:09

Mina Hafzalla


People also ask

How do I modify the URL without reloading the page?

Method 2: Adding a new state with pushState() Method: The pushState() method is used to add a new history entry with the properties passed as parameters. This will change the current URL to the new state given without reloading the page.

How do you update parameters in a URL?

The value of a parameter can be updated with the set() method of URLSearchParams object. After setting the new value you can get the new query string with the toString() method. This query string can be set as the new value of the search property of the URL object.


2 Answers

You can use the pushState or replaceState methods, i.e. :

window.history.pushState("object or string", "Title", "new url"); 

OR

window.history.replaceState(null, null, "?arg=123"); 

Example with argument:

var refresh = window.location.protocol + "//" + window.location.host + window.location.pathname + '?arg=1';     window.history.pushState({ path: refresh }, '', refresh); 
like image 127
Pedro Lobito Avatar answered Sep 23 '22 13:09

Pedro Lobito


If anyone wants to add a parameter to a more complex url (I mean, https://stackoverflow.com/questions/edit?newParameter=1), the following code worked for me:

var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?newParameter=1'; window.history.pushState({ path: newurl }, '', newurl); 

Hope this helps!

like image 42
pablobascones Avatar answered Sep 23 '22 13:09

pablobascones