How to Send POST Request with URL

How to Submit POST Request with A HTML Link ?

By default, all links in HTML are transmitted with GET request. However, as you designed a webpage, you may come across a situation where you want to submit POST request with a HTML link. For example, when you want create a Log In or Log Out link, you need to send the request as POST to be secure instead of GET. But you are maybe in a situation where you don’t want these links to be buttons. So, what do you do?

 

One option is to stylize your button as the link through a CSS trick. But this is not ideal because you still have to envelope your link around the post, and you need to include some complicated looking CSS codes just to decorate your button. And if you are using a CSS framework like Bootstrap, you need to go through the extra step to tweak your code further. Ugh.

 

A better option is to use a simple Javascript call to invoke the POST request. Let’s see how we can do this.

Let’s say I have a HTML file that is used for the sign out purpose.

<a href="">Sign Out</a>

Next, we call a Javascript function called “signOut()” whenever we click this link:

<a href="javascript: signOut();">Sign Out</a>

And somewhere between the body of HTML, ideally at the bottom of body section, we define the javascript function signOut():

function signOut() {
     document.formSignOut.submit();
}

Okay. So, every time the Sign Out link is clicked, the javascript function will be invoked. We still need to define a HTML form named “formSignout” and sending as POST request. We will send it to an arbitrary link called “/signout”, but it can be any other link that you want to redirect to. And we will make this form hidden with CSS’s display: none; property.

<div style="display: none;">
<form name="formSignout" action="/signout" method="post">
</form>

We do not have any attribute or field inside the form because only purpose for the form is to submit the POST request via Sign Out link.

That is all! See you next time.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s