Reputation: 10547
I can easily find how to submit an existing form using jQuery. But how can I, given a URL, and some parameters create and submit this form on the fly?
Upvotes: 2
Views: 5127
Reputation: 85145
This sounds like a bad solution to a problem that can probably be better solved another way...
That being said, you can create a form and trigger the submit method on it easily enough:
$([
'<form action="url.php" method="post">',
'<input type="hidden" name="param1" value="foo"/>',
'<input type="hidden" name="param1" value="foo"/>',
'</form>'
].join('')).appendTo('body')[0].submit();
If you need to be able to specify the parameters and the url then you could write a function similar to this one:
function submitValues(url, params) {
var form = [ '<form method="POST" action="', url, '">' ];
for(var key in params)
form.push('<input type="hidden" name="', key, '" value="', params[key], '"/>');
form.push('</form>');
jQuery(form.join('')).appendTo('body')[0].submit();
}
and call it this way:
submitValues('url.php', { foo: 'bar', boo: 'far' });
Upvotes: 9