Tag Archives: web development

Convert GET to POST with jQuery

A bit of code to convert GET values obtained from a clicked link in to a POST and send it as a post using jQuery.

If you generate href values in your code for dynamic effects with jQuery, you need to convert the href attribute in the <a>  tag to a post. I use the above code to do just that.

Say you have the following bit of html in your page:

If a user clicks that link, the browser performs a GET request for the page with those vars. If you would like to do something a bit more sexy than a GET, say, some animation, you need jQuery to step in.

With the code at the top of this post, we can alter this GET to a POST using jQuery thus:

Here we bind a click event to the “delete_item” class which overrides the browser default action of doing a GET. We then use jQuery’s $(this) , that is, the <a>  tag, to pull the href attribute from the link and split it where the question mark is.

The split()  method creates an array and assigns it to the “postvar” variable at the start of that line.

Given the above html example, this would give us the following array within postvar:

Now we can use jQuery’s $.post()  method to send the original request as a POST instead of a GET.

There, simple.

The only thing I can think of that would trip this code up is the use of a second ? within the href attribute, though why anyone would do that is a mystery since they should probably encode the question mark instead.

– Lewis