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.
1 2 3 4 5 6 7 8 9 10 |
$('.cssclass').click(function() { var postvar = $(this).attr("href").split('?'); $.post(postvar[0], postvar[1], function(i) { // Look after (i) or do magic. }); return false; }); |
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:
1 |
<a class="delete_item" href="dopoststuff.php?action=add&item=21" title="Delete item 21">Delete</a> |
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:
1 2 3 4 5 6 7 8 9 10 |
$('.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; }); |
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:
1 |
{ "dopoststuff.php", "action=add&amp;item=21" } |
Now we can use jQuery’s $.post() method to send the original request as a POST instead of a GET.
1 2 3 |
$.post(postvar[0], postvar[1], function(i) { // Look after (i) or do magic. }); |
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