My need is to send multiple values when a user clicks a button which uses GET METHOD. Since multiple values are to be sent, I am using an argument as follows:
$argument='var2=value2&var3=value3';
echo "<button value='value1&$argument&' type='submit' name='var1'>Send</button>";
Essentially, the button tag in HTML has a restriction that it can send ONLY one name-value pair. In this case, it will send name='var1'
and corresponding value as value1
. Hence, I am appending the other name-value pairs through the PHP $argument variable. In this case, var2=value2&var3=value3
are getting appended, and sent.
All good till here.
The problem is that when it reaches the submitted page, it is getting the following encoding: https://example.com/dir1/page.php?var1=value1&var2=value2&var3=value3&
Essentially, the & is getting &, and = is becoming =. I am aware that this is due to the inbuilt encodeURIComponent of HTML, but due to this encoding the form submission is failing.
I am looking for a way/method to receive the following in the submitted page (i.e. without encoding), so that it can be processed smoothly:
https://example.com/dir1/page.php?var1=value1&var2=value2&var3=value3&
PS: have explored existing threads like Escaping ampersand in URL & Why does & get decoded to & when passed as a parameter to a JavaScript function from a link? & many more, but unable to find the answer.
Also tried the following as mentioned in URL/HTML escaping/encoding, but not working:
echo "<button value='value1&".htmlspecialchars($argument)."' type='submit' name='var1'>Send</button>";
If any existing answer exists, pls point me to it in the comment before marking this question down. Thanks
CodePudding user response:
You can simply put these values individually in hidden fields in the form which the button is part of.
e.g.
<form>
<button type='submit' name='send'>Send</button>
<input type="hidden" name="var1" value="<?php echo htmlspecialchars($val1)?>">
<input type="hidden" name="var2" value="<?php echo htmlspecialchars($val2)?>">
</form>
The browser will then use these to create a properly-constructed and encoded URL for you automatically when the form is submitted.