Modifying a Query String Without Reloading the Page

How to change the querystring on the same page without postback

No, you cannot change the current query string without reloading. You could use the frgament portion of the url though (#). Setting the fragment portion might allow you to add some entries to the browser history without reloading.

For example if your current url is http://example.com/foo you could change it to http://example.com/foo#bar=baz without reloading the current page.

How do we update URL or query strings using javascript/jQuery without reloading the page?

Yes - document.location = "http://my.new.url.com"

You can also retrieve it the same way eg.

var myURL = document.location;
document.location = myURL + "?a=parameter";

The location object has a number of useful properties too:

hash            Returns the anchor portion of a URL
host Returns the hostname and port of a URL
hostname Returns the hostname of a URL
href Returns the entire URL
pathname Returns the path name of a URL
port Returns the port number the server uses for a URL
protocol Returns the protocol of a URL
search Returns the query portion of a URL

EDIT:
Setting the hash of the document.location shouldn't reload the page, just alter where on the page the focus is. So updating to #myId will scroll to the element with id="myId". If the id doesn't exist I believe nothing will happen? (Need to confirm on various browsers though)

EDIT2: To make it clear, not just in a comment:
You can't update the whole URL with javascript without changing the page, this is a security restriction. Otherwise you could click on a link to a random page, crafted to look like gmail, and instantly change the URL to www.gmail.com and steal people's login details.

You can change the part after the domain on some browsers to cope with AJAX style things, but that's already been linked to by Osiris. What's more, you probably shouldn't do this, even if you could. The URL tells the user where he/she is on your site. If you change it without changing the page contents, it's becomes a little confusing.

Remove a query string using react-router without reloading page?

You should be able to replace the state with a call to replace. The call to push will add a new entry to the history which break the previous button. The call to replace don't push but replace the current page.

const onClick = () => {
history.replace(pathWithoutTheQuery)
}


Related Topics



Leave a reply



Submit