How do i POST/Submit a form using Jquery?
From This answer and the fact i may be using an anti pattern I thought i should change the ajax call into behavior like submitting a form. I found $.post but that seems to be doing ajax and does not change the page i am on.
How do i submit a form with jquery or p开发者_StackOverflow中文版lain JS?
It's as simple as calling the $.submit()
method on the form itself:
$("#formID").submit(); // jQuery
document.getElementById("formID").submit(); // Javascript
Or if you're using the name attribute only:
$("form[name='formName']").submit(); // jQuery
document.formName.submit(); // Javascript
If you're only interested in redirecting the page after you submit the data, you could do this from the callback of the $.post()
call:
$.post("process.php", { 'foo':$(".bar").val() }, function(result) {
window.location = "thanks.php";
});
Update:
The asker indicated in the comments below that no form actually exists. I would suggest creating one:
var myForm = $("<form>")
.attr({'method':'post','action':'process.php'})
.appendTo("<body>");
And then adding your data:
$("<input>")
.attr({'type':'hidden','name':'firstname'})
.val("Jonathan")
.appendTo(myForm);
And later, when you're ready, submit it:
$(myForm).submit();
You can also do so asynchronously
var params = { 'key1' : 'value1' , 'key2' : 'value2' }; $.post( '/site/resource/' , params , function(ret) { alert(ret) } );
If you can submit as a get you could try some javascript like this:
window.location = 'http:/host/path?param=value¶m=value¶m=value'
You can even construct the string on the fly from all your data scattered in the DOM.
精彩评论