Is there any way of making a POST request when an svg image is clicked?
My best attempt so far looks like:
<form action="/test-button" method="POST"> <input name="Submit" type="submit" value="Submit" /> <svg > <rect width="100" height="100" > </svg> </form>
Which is a black rectangle with a submit button next to it.
I want to allow people to choose between several images, so this may be an ok solution, but is there any way of making an image which, when clicked, will fire off a POST?
Extra points for not using javascript.
To design the shape of an HTML button we can use SVG elements (Scalable Vector Graphics). It basically defines the vector-based graphics in XML format. Every element and every attribute in SVG files can be animated.
The simplest way to make a portion of an SVG clickable is to add an SVG hyperlink element to the markup. This is as easy as wrapping the target with an <a> tag, just as you would a nested html element. Your <a> tag can surround a simple shape or more complex paths. It can surround a group of SVG elements or just one.
SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document. If you did everything correctly, your webpage should look exactly like the demo below.
Just use text-align: center to do the horizontal centering, and set the SVG height to the <div> height and the the SVG engine will do the rest.
Warning: This is a little hacky, but as far as I know it's 100% legit, and doesn't need javascript.
Since the label
element can also be used to control it's associated input, you could try something like this:
<form action="/test-button" method="POST"> <label> <input type="submit" name="image" value="one"> <svg><rect width="100" height="100"></rect></svg> </label> <label> <input type="submit" name="image" value="two"> <svg><rect width="100" height="100"></rect></svg> </label> </form>
Then hide the submit buttons with CSS. You can put anything in the label that you want.
When you click on whatever's in the label, it will trigger the submit button inside it and submit the form, with the button's value
in the POST array.
There is also an <input type="image">
, but that's for an entirely different purpose (tracking coordinates of where it was clicked).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With