views:

51

answers:

4

Hello,

I am writing a basic wizard for my web site. It will have 4 steps, and each needs to have its own URL. Each step must first validate a form before moving on.

If the form for a given step fails to validate, I don't want the URL to change. But if it passes, I do want it to move on.

What is the preferred way to write this? Using javascript alone to validate is not secure enough. I have 2 ideas so far but I don't love either:

1) Post the form to the same script and use a header() redirect to the next step if it passes.
2) Send an ajax post to validate and then use location.href to send user to the next step if it passes.

Is there a better way to do this?

Thanks, Brian

+2  A: 

Your option #1 is exactly the way I'd do it.

timdev
+3  A: 

I would prefer option #1, since it doesn't require javascript.

However, you'll also want to consider what happens when somebody bookmarks or skips directly to the wrong step.

Eric Petroelje
Good caveat. Each step should inspect and validate session data from the previous steps, and take corrective action if necessary.
timdev
+1  A: 

Keep in mind that you can combine these two approaches so that:

  1. If the user has JS enabled, they get a smoother experience (no page reload)
  2. If they don't, no functionality is lost

You would do that using a standard trick:

<form name="foo" action="bar.php" method="post">
    <input type="submit" value="Submit Form" onclick="ajax_handler(); return false;" />
</form>

This will require some competent engineering so that ajax_handler() can utilize the same code as bar.php does to process the form data. Also, you should pay special attention in the AJAX path so that things like the back button continue to work as the user expects.

Jon
+1  A: 

Another option would be to have all the validation logic (between this steps) in one single PHP page (which then always gets POSTed to).

At postback, do the validation for the current step and (only if valid) branch out to the next step. You also need to persist the 'previous' validations between posts.

You can still have different URL's in the sense of myform.php?step=1 and myform.php?step=2 and ... With some simple url rewriting that could be myform/step1, myform/step2, ...

ChristopheD