1

I have http://localhost/?val=1

When I click on a link, is there a way this link can append a query variable to the current string, for example:

<a href="&var2=2">Link</a> 

so when I click it the url would be:

http://localhost/?val=1&var2=2 

but when I click the link it removes the first query string and looks like

http://localhost/&var2=2

Is such a thing possible with normal HTML?

teo van kot
  • 12,350
  • 10
  • 38
  • 70
user3704920
  • 617
  • 1
  • 8
  • 19
  • `Is such a thing possible with normal HTML?` - do you mean using HTML only? No. You have to use JavaScript. – Madbreaks Jan 13 '15 at 22:42
  • it's better to use `js` variable to add and delete params and then you can use this [answer](http://stackoverflow.com/a/111545/1849444) to create quaery string. – teo van kot Jan 13 '15 at 22:43
  • better try with index.php?var1=1&var2=2 ,hope if you follow this style ,it would be helpful. – jewelhuq Jan 13 '15 at 22:55
  • With just HTML absolutely not. But you can use javascript or a better way; Just fetch the current request Query String and print it again in the href: Link – Hosein Jan 13 '15 at 23:04

2 Answers2

2

You can't do that using only html, but you can do it with js or php:

Using JS:

<a onclick="window.location+=((window.location.href.indexOf('?')+1)?'':'?')+'&var2=2'">Link</a>

Using Php:

<a href="<?php echo basename($_SERVER['PHP_SELF'])."?".$_SERVER['QUERY_STRING']."&var2=2" ?>">Link</a>

Notice 1: make sure you don't have the new variable in the current link, or it'll be a loop of the same variable

Notice 2: this is not a professional way, but it could work if you need something fast.

Baraa Al-Tabbaa
  • 753
  • 5
  • 11
0

Basically you want to get your current URL via JavaScript with:

var existingUrl = window.location.href; // http://localhost/?val=1

Then append any Query Strings that are applicable using:

window.location.href = existingUrl + '&var2=2';

or some other similar code. Take a look at this post about Query Parameters.

Note: A link would already have to exist with an OnClick event that calls a function with the above code in it for it to work appropriately.


Now obviously this isn't very useful information on it's own, so you are going to want to do some work either in JavaScript or in Server code (through use of NodeJS, PHP, or some other server-side language) to pass those variable names and their values down so that the button can do what you are wanting it to do.

You will have to have some logic to make sure the query parameters are put in the URL correctly though. I.E. if there is only one query param it's going to look like '?var1=1' and if it's any subsequent parameter it's going to look like '&var#=#'.

Community
  • 1
  • 1
Kody
  • 905
  • 9
  • 19