views:

74

answers:

3

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?

+9  A: 

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();
Jonathan Sampson
problem is, i dont have a form. I grab the post data inside of a <div> add in a few more then need to send it. -edit- actually theres a few places were i get info from which made my code simpler to read and maintain. Problem is now i must either inject the data in a form when submitting or submit somehow via js
acidzombie24
You should ask "how do I submit a form" if no form exists to submit :)
Jonathan Sampson
I would suggest creating a form element on the fly, then submitting that.
Jonathan Sampson
hmm, is there an easy way to do that? should i continue doing an ajax submit then window.location = url when it succeeds (and err msg on fail)? I;m thinking which one is easier to maintain and wont kill the server.
acidzombie24
See my updated answer.
Jonathan Sampson
@acidzombie24: I don't know which is appropriate for your project. If you don't need the page to immediately redirect, you can stick with `$.post()` and simply change the `window.location` in the callback.
Jonathan Sampson
great and quick details +1
Sarfraz
acidzombie24
A: 

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.

rmarimon
this would do a GET request
George
A: 

You can also do so asynchronously

var params = { 'key1' : 'value1' , 'key2' : 'value2' };
$.post( '/site/resource/' , params , function(ret) { alert(ret) } );
George