19

I thought this would be quite simple but the documentation doesn't point me to any solution. I am working on an editor. While i am using $.ajax for saving multiple forms at once i would like to perform the same post but with a complete page reload. how can i achieve that?

Trigger Preview BTN -> Collect Forms -> Regular post to preview.php -> Render preview.php

Any ideas?

Thank you very much!

Bosh
  • 1,237
  • 1
  • 16
  • 23

2 Answers2

10

The simplest way is to just use a normal <form> and a redirect from the server-side. Just use one <form> with all your inputs, no need for JavaScript at all.


If you need to move the elements in preparation for submission (since <form> elements can't be validly nested) then on the jQuery side all you need is to copy the elements into your single <form> (they should have unique names unless you want overlap), like this:

<form id="bigForm" method="post"></form>

Then in jQuery when you want to submit:

$("form :input").appendTo("#bigForm");
$("#bigForm").submit();
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • hehe yes i shouldnt use js if its not necessary... Didnt see the most simplest solution $('form').submit()... So is it true that i need to append "action=preview.php" to each form and $('form').submit() sends them all at once to preview.php... Will give that a try... Thank you! – Bosh Oct 10 '10 at 10:27
  • @Bosh - That won't work for submitting *multiple* forms, rather structuring your page to only use one form initially :) For the others that you're submitting via AJAX you could have `
    ` containers for example, and just use `$("#thatDiv :input").serialize()` to get their data.
    – Nick Craver Oct 10 '10 at 10:34
  • .. Ok that's what i am already doing on save. So what i am trying now is to append the serialized data to a one-field form and perform a regular submit for the preview... Thank you! Yes i really would have liked to structure the document to hold one form only but in that case i prefer to stick to multiple forms. ;-) thanks! – Bosh Oct 10 '10 at 10:43
  • This approach was used to create jQuery.form() or $.form() in [jQuery post request (not Ajax)](http://stackoverflow.com/questions/4583703/jquery-post-request-not-ajax) – Peter V. Mørch May 22 '13 at 18:14
  • This doesn't seem to be elegant solution. Suppose I have some dynamic data, and I want to post it (no ajax). Your suggestion offers to generate multiple hidden inputs in form and then ".submit()" it. Is it really best solution? – 83lynx Aug 22 '13 at 14:39
2

But if you still want to control this in Javascript, then you can simply reload page after $.post request is done or use $('form').submit(); so initiate normal submiting.

Māris Kiseļovs
  • 16,957
  • 5
  • 41
  • 48