Turn a form in a link and send it via POST
Backend devs sometimes make bad things, something like a form with only hidden inputs. I dont like it. This is an example:
<form action="/to/next/page">
<input type="hidden" name="next-page" id="next-page" value="3" />
<input type="submit" value="Next" />
</form>
If you only have access to the front and want to make it looks better, you can do something like this:
First of all, turn form in a link
<a href="/to/next/page?next-page=3">Next</a>
Oh! Beauty!
Make this little code to intercept the click and send the post
$('#my-link').click(function() {
// Memo this to use latter
var myLink = $(this);
// Now i have the href content
var href = myLink.attr('href');
// And now i have a array, position 0 is our URL and position 1 is our params
var hrefSplited = href.split('?');
// Making the magic, turn my string params in a object
var params = JSON.parse('{"' + decodeURI(hrefSplited[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}');
// Making the pot
// The first params is the first part of href, the url
$.post(hrefSplited[0],
params,
function(data){
alert('Success, link submited via post');
}
);
// Prevent the link to follow
return false;
});
It is just an example, maybe you can find other implementations for:
var params = JSON.parse('{"' + decodeURI(hrefSplited[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}');
Written by Luiz Fernando de Souza Filho
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Jquery
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#