0

I'm trying to create or append new queries to the URL without refresh.

Current solution

PHP

echo'<a href="" onclick="addOrUpdateUrlParam(\'doorid\', ' . $row["door_style_id"] . '); return false;">';

JS

function addOrUpdateUrlParam(name, value)
{
  var href = window.location.href;
  var regex = new RegExp("[&\\?]" + name + "=");
  if(regex.test(href))
  {
    regex = new RegExp("([&\\?])" + name + "=\\d+");
    window.location.href = href.replace(regex, "$1" + name + "=" + value);
  }
  else
  {
    if(href.indexOf("?") > -1)
      window.location.href = href + "&" + name + "=" + value;
    else
      window.location.href = href + "?" + name + "=" + value;
  }
}

This works perfectly for appending or creating new queries as intended. But refreshes the page on click.

Any help appreciated, thanks.

Sam Walker
  • 21
  • 3
  • 1
    Does this answer your question? [How do I modify the URL without reloading the page?](https://stackoverflow.com/questions/824349/how-do-i-modify-the-url-without-reloading-the-page) – Nico Haase Apr 03 '20 at 12:10
  • Please search for similar problems before posting new questions – Nico Haase Apr 03 '20 at 12:10
  • Try using [history.pushState()](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) `history.pushState(null, null, window.location.href + '/foobar' );` – Gavin Apr 03 '20 at 12:12
  • are you just trying to update the address bar? – developer Apr 03 '20 at 12:13
  • @developer without a refresh is the important part here, at the moment the webpage refreshes on click. – Sam Walker Apr 03 '20 at 12:16
  • I don't know the scope of your problem - what i mean is - do you need to update the address bar? or can you store the url in a separate variable until you need to use it? or maybe you are talking about running the query in the background - i.e. with ajax – developer Apr 03 '20 at 12:19
  • @Gavin I'm not familiar with js history use. Would this essentially replace the use of `window.location.href = ` – Sam Walker Apr 03 '20 at 12:20
  • @developer I would need to update the address bar immediately on click – Sam Walker Apr 03 '20 at 12:20
  • Then i would look at @NicoHaase comment – developer Apr 03 '20 at 12:22

0 Answers0