简体   繁体   中英

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 plain 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&param=value&param=value'

You can even construct the string on the fly from all your data scattered in the DOM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM