Make a link use POST instead of GET
Asked Answered
L

11

283

I'm not sure if this is even possible. But I was wondering if anyone knows how to make a hyperlink pass some variables and use POST (like a form) as opposed to GET.

Legnica answered 12/10, 2010 at 14:52 Comment(2)
HTML can't do that. JavaScript can catch the click event on the link and do what you want if you can't change HTML and CSS can style button like links if it's only a matter of appearance.Irvine
It's true, HTML can't do that. The answers all recommend using a <form> with a submit button that's styled to look like a link. Making an actual link use the http POST method, as the question asks, is not possible.Callboard
T
117

You create a form with hidden inputs that hold the values to be posted, set the action of the form to the destination url, and the form method to post. Then, when your link is clicked, trigger a JS function that submits the form.

See here, for an example. This example uses pure JavaScript, with no jQuery — you could choose this if you don't want to install anything more than you already have.

<form name="myform" action="handle-data.php" method="post">
  <label for="query">Search:</label>
  <input type="text" name="query" id="query"/>
  <button>Search</button>
</form>

<script>
var button = document.querySelector('form[name="myform"] > button');
button.addEventListener(function() {
  document.querySelector("form[name="myform"]").submit();
});
</script>
Tereus answered 12/10, 2010 at 14:55 Comment(6)
You can't have an A sent POST without javascript. Only a form can do that (or AJAX or JS for the matter). So this is a workaround: create a hidden form, and have the A link submit it via JS.Tereus
I updated your answer to use more modern approach. If you disagree, feel free to rollback this edit.Work
You can use a similar strategy with the form being set to display:none; somewhere else on the page.Rambunctious
There is no reason to involve Javascript in this process. Why is this the accepted answer?Efflorescent
@Efflorescent Because neither answer is perfect. If you're already using JS, which the OP may be, then it's much better than trying to redecorate a button as a link using CSS and finding you've missed unsetting a button style when SuperBrowser V1.2 comes out.Epistemology
Am I missing something or if you removed the script tag it would work exactly the same lolOperation
B
442

You don't need JavaScript for this. Just wanted to make that clear, since as of the time this answer was posted, all of the answers to this question involve the use of JavaScript in some way or another.

You can do this rather easily with pure HTML and CSS by creating a form with hidden fields containing the data you want to submit, then styling the submit button of the form to look like a link.

For example:

.inline {
  display: inline;
}

.link-button {
  background: none;
  border: none;
  color: blue;
  text-decoration: underline;
  cursor: pointer;
  font-size: 1em;
  font-family: serif;
}
.link-button:focus {
  outline: none;
}
.link-button:active {
  color:red;
}
<a href="some_page">This is a regular link</a>

<form method="post" action="some_page" class="inline">
  <input type="hidden" name="extra_submit_param" value="extra_submit_value">
  <button type="submit" name="submit_param" value="submit_value" class="link-button">
    This is a link that sends a POST request
  </button>
</form>

The exact CSS you use may vary depending on how regular links on your site are styled.

Bridle answered 23/11, 2015 at 21:24 Comment(13)
agreed. I needed a way to do this in a email, so JS wasn't much of an option for me. This should work perfectlyDeloisedelong
I'm only able to upvote this once. That is almost as sad as the fact that 99.728% of all HTML questions will end up being confused with Javascript or jQuery problems.Chamomile
u can make color: #0275D8 for the same colorAngularity
This is for sure a simple way to use a button that looks like a link, but it is actually hard-coding. You have to know exactly the conditions that this button is going to live into and set them explicitly for every case. I think that the answers that are based on JS/JQuery are more generic since they are using the link element itself (or whichever element).Carolanncarole
@Carolanncarole If you need to be able to change the data you're submitting dynamically based on some arbitrary conditions on the page, then yeah you will need JavaScript. That's true though for regular links that use GET just as much as it is for "links" that use POST.Bridle
@Bridle Sorry, my comment was not so clear: I mainly try to say that this button is styled specifically to look like a <a> element. But if you put the button around other <a> elements that are styled differently e.g. in different parts of the page you have to duplicate all the css rules of the <a> also for the button, to create rules for hover, visited etc. Otherwise it will of course do the job, but it will look ugly. With the other solutions you simply don't need to change any CSS, you just get an <a> element like all the other you already have. Of course pure HTML also has some advantages.Carolanncarole
Is there anyway to make this work for PUT/DELETE/OPTIONS?Tenure
@J.Money No. See softwareengineering.stackexchange.com/q/114156/94235 If you need PUT or DELETE, you'll need to use JavaScript.Bridle
But a button, even if it's styled like a hyperlink, isn't a hyperlink, right? How is the user able to open the post result in a new tab via the browser context menu?Linlithgow
@Linlithgow AFAIK, none of the other proposed solutions work with middle-click either. If you really want to be pedantic, you might say that submitting a POST request with a link is impossible. You can only submit POST requests with forms and JavaScript.Bridle
Even though this answer looks creative and cool, the question asks how to use a hyperlink to generate a POST request. Changing a submit button's appearance so it looks like a link is not the answer. I'm sure if that's what's needed the question would have stated that.Bondman
When you click on the link in an email, Gmail will warn the recipient with a popup saying "You're submitting information to an external page". Browsers will also block the pop up by default and the user has to manually allow that popupMarcelline
Current version of Chrome also sets display to inline-block and text-align to center, on buttons, so these now need to be added to list of properties to change, or there is weird spacing around the link.Epistemology
T
117

You create a form with hidden inputs that hold the values to be posted, set the action of the form to the destination url, and the form method to post. Then, when your link is clicked, trigger a JS function that submits the form.

See here, for an example. This example uses pure JavaScript, with no jQuery — you could choose this if you don't want to install anything more than you already have.

<form name="myform" action="handle-data.php" method="post">
  <label for="query">Search:</label>
  <input type="text" name="query" id="query"/>
  <button>Search</button>
</form>

<script>
var button = document.querySelector('form[name="myform"] > button');
button.addEventListener(function() {
  document.querySelector("form[name="myform"]").submit();
});
</script>
Tereus answered 12/10, 2010 at 14:55 Comment(6)
You can't have an A sent POST without javascript. Only a form can do that (or AJAX or JS for the matter). So this is a workaround: create a hidden form, and have the A link submit it via JS.Tereus
I updated your answer to use more modern approach. If you disagree, feel free to rollback this edit.Work
You can use a similar strategy with the form being set to display:none; somewhere else on the page.Rambunctious
There is no reason to involve Javascript in this process. Why is this the accepted answer?Efflorescent
@Efflorescent Because neither answer is perfect. If you're already using JS, which the OP may be, then it's much better than trying to redecorate a button as a link using CSS and finding you've missed unsetting a button style when SuperBrowser V1.2 comes out.Epistemology
Am I missing something or if you removed the script tag it would work exactly the same lolOperation
T
54

You can use javascript functions. JQuery has a nice post function built in if you decide to use it:

JQuery Post

<script language="javascript"> 

   function DoPost(){
      $.post("WhateverPage.php", { name: "John", time: "2pm" } );  //Your values here..
   }

</script>


<a href="javascript:DoPost()">Click Here</A> 
Tundra answered 12/10, 2010 at 14:56 Comment(6)
This does make the POST request as asked, but I couldn't use this because I still need to go to the location "Whatever.php".Gpo
$.post('page.php', {param: 1}, function() { window.location.href = 'page'.php' });Spathose
@mplungjan href says where the link is referring to, while I agree that it's wrong to confuse behavior and content, in this case javascript is the reference. In other words "when you click the link it will perform a postback using JavaScript". This has more meaning than binding a click event. Hard rules like "dont ever use javascript in href" are as bad as any other bad practice.Bondman
@Bondman I said: not recommended. - not "don't ever use". If you really want to you can do <a href="whyjavascript.html" id="postIt">Click Here</a> and have $("#postIt").on("click",function(e) { e.preventDefault(); $.post("WhateverPage.php", { name: "John", time: "2pm" } ); });Accompany
@Accompany that recommendation like any other is introduced to avoid confusing content/behavior. When a recommendation is brought forward in cases outside it's intended scope it starts to appear as a hard-rule. The example you gave appears to go an extra mile just to be on the safe side of the "rule" so noone can blame the programmer in the future but this safety is achieved at the cost of readability and meaning. It's just how it appears to another pragmatic developer but I'm sure you didn't mean that.Bondman
Thanks for your solution. Could you explain, how to load page, as if it was sent by form? window.location.href doesn't work, because it loads as GET.Shirleneshirley
M
29

This is an old question, but none of the answers satisfy the request in-full. So I'm adding another answer.

The requested code, as I understand, should make only one change to the way normal hyperlinks work: the POST method should be used instead of GET. The immediate implications would be:

  1. When the link is clicked we should reload the tab to the url of the href
  2. As the method is POST, we should have no query string in the URL of the target page we load
  3. That page should receive the data in parameters (names and value) by POST

I am using jquery here, but this could be done with native apis (harder and longer of course).

<html>
<head>
    <script src="path/to/jquery.min.js" type="text/javascript"></script>
    <script>
        $(document).ready(function() {

            $("a.post").click(function(e) {
                e.stopPropagation();
                e.preventDefault();
                var href = this.href;
                var parts = href.split('?');
                var url = parts[0];
                var params = parts[1].split('&');
                var pp, inputs = '';
                for(var i = 0, n = params.length; i < n; i++) {
                    pp = params[i].split('=');
                    inputs += '<input type="hidden" name="' + pp[0] + '" value="' + pp[1] + '" />';
                }
                $("body").append('<form action="'+url+'" method="post" id="poster">'+inputs+'</form>');
                $("#poster").submit();
            });
        });
    </script>
</head>
<body>
    <a class="post" href="reflector.php?color=blue&weight=340&model=x-12&price=14.800">Post it!</a><br/>
    <a href="reflector.php?color=blue&weight=340&model=x-12&price=14.800">Normal link</a>
</body>
</html>

And to see the result, save the following as reflector.php in the same directory you have the above saved.

<h2>Get</h2>
<pre>
<?php print_r($_GET); ?>
</pre>

<h2>Post</h2>
<pre>
<?php print_r($_POST); ?>
</pre>
Mofette answered 30/11, 2014 at 0:22 Comment(0)
W
13

Another working example, using similar approach posted : create a html form, use javascript to simulate the post. This does 2 things : post data to a new page and open it in a new window/tab.

HTML

<form name='myForm' target="_blank" action='newpage.html' method='post'>
<input type="hidden" name="thisIsTheParameterName" value="testDataToBePosted"/>
</form>

JavaScript

document.forms["myForm"].submit();
Wingfield answered 24/12, 2013 at 3:24 Comment(0)
A
11

Instead using javascript, you could also use a label sending a hidden form. Very simple and small solution. The label can be anywhere in your html.

<form style="display: none" action="postUrl" method="post">
  <button type="submit" id="button_to_link"> </button>
</form>
<label style="text-decoration: underline" for="button_to_link">  link that posts </label>
Anacreontic answered 19/6, 2020 at 12:26 Comment(3)
This solution was what I ended using. Not needing JavaScript is a plus.Percale
The use of label is very nice as it allows inlining the hyperlink in flow content such as <p>, which cannot be done with the other form solutions in this thread. This should be the accepted answer imo.Bharat
For accessibility concerns, we should add tabindex=0 to the label to make it tabbale for keyboard users.Bharat
C
4

HTML + JQuery: A link that submits a hidden form with POST.

Since I spent a lot of time to understand all these answers, and since all of them have some interesting details, here is the combined version that finally worked for me and which I prefer for its simplicity.

My approach is again to create a hidden form and to submit it by clicking a link somewhere else in the page. It doesn't matter where in the body of the page the form will be placed.

The code for the form:

<form id="myHiddenFormId" action="myAction.php" method="post" style="display: none">
  <input type="hidden" name="myParameterName" value="myParameterValue">
</form>

Description:

The display: none hides the form. You can alternatively put it in a div or another element and set the display: none on the element.

The type="hidden" will create an fild that will not be shown but its data will be transmitted to the action eitherways (see W3C). I understand that this is the simplest input type.

The code for the link:

<a href="" onclick="$('#myHiddenFormId').submit(); return false;" title="My link title">My link text</a>

Description:

The empty href just targets the same page. But it doesn't really matter in this case since the return false will stop the browser from following the link. You may want to change this behavior of course. In my specific case, the action contained a redirection at the end.

The onclick was used to avoid using href="javascript:..." as noted by mplungjan. The $('#myHiddenFormId').submit(); was used to submit the form (instead of defining a function, since the code is very small).

This link will look exactly like any other <a> element. You can actually use any other element instead of the <a> (for example a <span> or an image).

Carolanncarole answered 3/10, 2016 at 17:50 Comment(0)
P
2

You can use this jQuery function

function makePostRequest(url, data) {
    var jForm = $('<form></form>');
    jForm.attr('action', url);
    jForm.attr('method', 'post');
    for (name in data) {
        var jInput = $("<input>");
        jInput.attr('name', name);
        jInput.attr('value', data[name]);
        jForm.append(jInput);
    }
    jForm.submit();
}

Here is an example in jsFiddle (http://jsfiddle.net/S7zUm/)

Piane answered 12/2, 2014 at 21:46 Comment(1)
@DaoLam the code actually works. I substituted leserged.free.fr/phpinfo.php for the value in phpref and it posted the form to that site passing in the values.Steffens
M
2

As mentioned in many posts, this is not directly possible, but an easy and successful way is as follows: First, we put a form in the body of our html page, which does not have any buttons for the submit, and also its inputs are hidden. Then we use a javascript function to get the data and ,send the form. One of the advantages of this method is to redirect to other pages, which depends on the server-side code. The code is as follows: and now in anywhere you need an to be in "POST" method:

<script type="text/javascript" language="javascript">
function post_link(data){

    $('#post_form').find('#form_input').val(data);
    $('#post_form').submit();
};
</script>

   <form id="post_form" action="anywhere/you/want/" method="POST">
 {% csrf_token %}
    <input id="form_input" type="hidden" value="" name="form_input">
</form>

<a href="javascript:{}" onclick="javascript:post_link('data');">post link is ready</a>
Monty answered 2/7, 2019 at 13:42 Comment(0)
T
1

Check this it will help you

$().redirect('test.php', {'a': 'value1', 'b': 'value2'});
Toowoomba answered 26/9, 2017 at 5:39 Comment(1)
You should mention that this solution needs the following library: github.com/mgalante/jquery.redirectKimberelykimberlee
C
0

I suggest a more dynamic approach, without html coding into the page, keep it strictly JS:

$("a.AS-POST").on('click', e => {
  e.preventDefault()
  let frm = document.createElement('FORM')
  frm.id='frm_'+Math.random()
  frm.method='POST'
  frm.action=e.target.href
  document.body.appendChild(frm)
  frm.submit()
})
Cranford answered 3/11, 2019 at 10:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.