views:

47

answers:

3

When doing web programming there seem to be two different ways of handling a form and its action. Is there a reason to prefer one method over the other?

Method 1: One page that displays a form or handles a submitted form. This seems simple, in that there's one form for everything. But it also means the if/else cases can become rather large.

if [form has not been submitted] {
    // display form for user input
} else {
    // handle submitted form
}

Method 2: Handle user input on one page with a form, with the form submitting to a second page.

page 1 (input.html):

<form action="./submit.html">
    // display form for user input
</form>

page 2 (submit.html): Handles the input from the form.

I've seen both of these methods used. The upside of the first method is that there's only one page and one set of variables to worry about, but the page can get large. In the second method, each file is simpler and shorter, but now you have twice as many files to worry about and maintain.

+2  A: 

I typically submit back to the same page, as you will often need to redisplay the initial page if there are validation errors.

Once the record has been successfully saved, I typically use the Post/Redirect/Get method to avoid the common multiple submit issue.

RedFilter
+1 on Post/Redirect/Get. This also stops the cryptic "do you want to resend the POST data" message most browsers display when you try to use the Back button from a page generated in response to a POST request.
Ken Keenan
A: 

I think it depends on what kind of form it is. If it has too much validation I would go with two pages.

I always use to pages though because I like my code to be clean, but I use AJAX whenever possible e.g. contact forms since they are short, and I just post the response back to a div in the form.

SoftwareDev
A: 

Caching.

If the server has a series of static HTML pages livened maybe only by AJAX (and even these requests cached, server side, per user), it reduces its load and traffic significantly. Then confining the dynamic content of targets of forms to a relatively small area is a boon, because a page that is a target of POST can't be retrieved from the cache, it has to be regenerated from scratch no matter how heavily loaded it is.

Of course this doesn't solve the question of n static pages + 1 CGI vs n static pages + m CGI. But once you don't need to spit out sophisticated HTML, just a simple redirect, keeping things in one place may be profitable - error checking and handling, authentication, session management and so on.

OTOH if every your page is a CGI script that creates a new page on each visit, there is no reason why it can't accept form data and handle it at the same time.

SF.