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.

<p style="padding-left: 30px;">$('.cssclass').click(function() {

var postvar = $(this).attr("href").split('?');

$.post(postvar[0], postvar[1], function(i) {
// Look after (i) or do magic.
});

return false;
});</p>

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:

<p style="padding-left: 30px;"><a class="delete_item" href="dopoststuff.php?action=add&amp;item=21" title="Delete item 21">Delete</a></p>

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:

<p style="padding-left: 30px;">$('.delete_item').click(function() {

var postvar = $(this).attr("href").split('?');

$.post(postvar[0], postvar[1], function(i) {
// Look after (i) or do magic.
});

return false;
});</p>

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:

<p style="padding-left: 30px;">{ "dopoststuff.php", "action=add&amp;item=21" }</p>

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

<p style="padding-left: 30px;">$.post(postvar[0], postvar[1], function(i) {
// Look after (i) or do magic.
});</p>

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