Making href (anchor tag) request POST instead of GET?

emilly picture emilly · Jan 3, 2014 · Viewed 162.2k times · Source
<a href="employee.action" id="employeeLink">Employee1</a>

when i click the Employee1 link, GET request goes to server. I want to make it POST instead of GET request. Is there a way i can change default GET behaviour of href?

Note:- I know it can be done where we can call javascript function on hyperlink click , then create form and submit it. But i am looking where we can mention some attribute in anchor tag to make POST request instead of GET request?

Answer

mplungjan picture mplungjan · Jan 3, 2014

Using jQuery it is very simple assuming the URL you wish to post to is on the same server or has implemented CORS

$(function() {
  $("#employeeLink").on("click",function(e) {
    e.preventDefault(); // cancel the link itself
    $.post(this.href,function(data) {
      $("#someContainer").html(data);
    });
  });
});

If you insist on using frames which I strongly discourage, have a form and submit it with the link

<form action="employee.action" method="post" target="myFrame" id="myForm"></form>

and use (in plain JS)

 window.onload=function() {
   document.getElementById("employeeLink").onclick=function() {
     document.getElementById("myForm").submit();
     return false; // cancel the actual link
   }
 }

Without a form we need to make one

 window.onload=function() {
   document.getElementById("employeeLink").onclick=function() {
     var myForm = document.createElement("form");
     myForm.action=this.href;// the href of the link
     myForm.target="myFrame";
     myForm.method="POST";
     myForm.submit();
     return false; // cancel the actual link
   }
 }