Let's say a user goes to example.com/example.html?one=foo
How could I make a link so that it appends another url variable like: example.com/example.html?one=foo&two=bar
I've tried <a href="?two=bar">Click here</a> but that just replaces the existing variable with a new one

How could I do this?
Thanks in advance

Dani AI

Generated

's example with a bare query string replaces the whole query because href="?two=bar" sets the page's query to exactly two=bar rather than merging it. As noted, that requires scripting; 's server-side PHP is a fine server-side fix. Below is a concise client-side approach using the modern URL / URLSearchParams APIs that preserves existing parameters and adds (or replaces) the named key.

document.addEventListener('DOMContentLoaded', function() {
  var anchors = document.querySelectorAll('a.append-two');
  for (var i = 0; i < anchors.length; i++) {
    var a = anchors[i];
    var u = new URL(window.location.href);
    // use set() to replace an existing 'two', or append() to create duplicates
    u.searchParams.set('two', 'bar');
    a.href = u.toString();
  }
});

Notes and gotchas: searchParams.set() replaces any existing value for the same key; searchParams.append() will create multiple entries for the same key (some servers treat duplicates differently). URL and URLSearchParams handle encoding automatically; for very old browsers a small manual parser or a polyfill is necessary. To update the browser address bar without navigating (single-page apps), use history.pushState:

var u = new URL(window.location.href);
u.searchParams.set('two', 'bar');
history.pushState(null, '', u.toString());

When links must be available to non-JS clients or rendered for SEO, the server-side method (as shown by ) is safer. Otherwise the client-side pattern above is simple, robust, and keeps existing query parameters intact.

Recommended Answers

All 6 Replies

You'll need some scsripting to do this. I don't think it's possible with plain HTML.

Didn't think it would be. Any ideas how?

What do you want to use, Javascript, PHP, something else?

Prefrably javascript but PHP would be fine

You want a link that links back to the same page, but with an extra variable tacked on? Did I understand correctly?

<?php 
    $thisPage = htmlentities($_SERVER['PHP_SELF']);
    $hasVar = strpos($thispage, '?');
    if($hasVar === FALSE)   // Check if there is already a variable on the URL
        $url = $thisPage . '?two=bar';  // if not, use ? to start query string
    else
        $url = $thisPage . '&two=bar';  // if yes, use & to append variable
?>
<a href="<?php echo $url; ?>">link</a>

Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.