0

I am wondering is there any solution to change or update the URL's query string part (visible in the browser's address bar) with some new values by clicking on some checkboxes through JavaScript or Jquery. I want to do this without any jQuery plugin.

When the user will click on any checkbox in a group then the data will be fetched from the database based on the user's selected value of checkbox. Along with it, the query string of URL will also be changed with new updated value. Note that the page will never be reloaded in this whole procedure. We can run through AJAX when checkbox is checked. How we can achieve this? A demo will be very much appreciated.

Sachin
  • 1,646
  • 3
  • 22
  • 59
  • 2
    Possible duplicate of [Updating address bar with new URL without hash or reloading the page](http://stackoverflow.com/questions/3338642/updating-address-bar-with-new-url-without-hash-or-reloading-the-page) – İbrahim Duran Jul 31 '16 at 08:04
  • http://stackoverflow.com/questions/824349/modify-the-url-without-reloading-the-page – Rahul Patel Jul 31 '16 at 08:19

2 Answers2

0

Yeah, this is a very common thing to do. window.replaceState is the function you're looking for. Alternatively you could also use pushState if you want to allow the user to be able to go back to the previous state of checkboxes, but that's more work and not always expected.

Then again, you actually need something to change one URL into another. Manipulating the URL as string is counter productive, so instead you can use a library like URI.js.

Kos
  • 70,399
  • 25
  • 169
  • 233
0

Use window.history like so :

window.history.pushState('page2', 'Title', '/new-uri');

For your case , you will have 2 nested functions: Event Listener which contains AJAX call + Callback of this ajax call :

 $('[input]').change(function(){
       if(this.checked){
           //AJAX
           $.get("URL",{},function(data){
                 //AJAX - Callback
                 window.history.pushState('page2', data.title, data.url);

             });

      }
});
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
  • if you handle `pushState` then you also need to handle `onpopstate` event. Otherwise you break the back button in the user browser. `replaceState` is simpler instead of `pushState` because it doesn't add a separate step in history. – Kos Jul 31 '16 at 08:15