Search code examples
javascriptjquery

Add (get) params to url without page reload?


With my code below I push every selected element to a array. I can push it to a url param with javascript like window.location.href. Can I add params to url without page reloading/redirect?

var keys = [];
keys.push({selected_element:object.key});

Needed structure is: /index.php?element[]=546454&element[]=156151&element[]=343141


Solution

  • You can use history.pushState...:

    if (history.pushState) 
    {
        var newQueryString = window.location.protocol + "//" + 
        window.location.host + window.location.pathname + 
        '?newStuff[]=123&whatever=909';
    
        window.history.pushState({path:newQueryString},'',newQueryString);
    }