← Psycopg2 has a web site? Sweet! | Gwibber is... →

Submitting links via POST using jQuery

Often, when designing interactive websites, you want to have elements that look like links, but submit POST requests, because they modify some data on your website. Maybe it's a delete link. Maybe it's a "Like" button. Today, I just stumbled across a dead easy way to do this using JQuery.

This method is clean and elegant. It doesn't require much any pollution of your HTML, except for a small, unobtrusive form at the end, and the javascript is straightforward and easy to follow. On the downside, it requires Javascript (and JQuery). If you don't have javascript installed, it submits the links as GET requests, which should not perform the requested action, as the whole point of this is to allow links to point to resources that require POST requests.

You aren't submitting any data, so we start with an empty form, specifying that you will be using POST, but with an empty "action" attribute, as we'll be supplying that dynamically. You can put this form at the bottom of your document body, and you only need one per page, regardless of how many links you have that need to be POSTed.

The form is essentially empty, though if you are using CSRF protection or honeypot fields, you may need to include them. I'm using Django, so my form looks like this:

<form id='post_link_form' action='' method='POST'>
  {% csrf_token %}
</form>

Next, load the following javascript on page load:

$('a.post_link').click(function () {
    $('#post_link_form').attr('action', this.href).submit();i
    return false;
});

And that's it. All you need to do to use it is add a class of post_link to every link you want to submit via POST, and then on the other end, have the resources in question require POST requests.

(With thanks to @pmclanahan.)

Comments !