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?

4
  • Is such a thing possible with normal HTML? - do you mean using HTML only? No. You have to use JavaScript. Commented Jan 13, 2015 at 22:42
  • it's better to use js variable to add and delete params and then you can use this answer to create quaery string. Commented Jan 13, 2015 at 22:43
  • better try with index.php?var1=1&var2=2 ,hope if you follow this style ,it would be helpful. Commented Jan 13, 2015 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: <a href="?val=1&var2=2">Link</a> Commented Jan 13, 2015 at 23:04

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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#=#'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.