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
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.
Your option #1 is exactly the way I'd do it.
Keep in mind that you can combine these two approaches so that:
- If the user has JS enabled, they get a smoother experience (no page reload)
- 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.
Another option would be to have all the validation logic (between this steps) in one single PHP page (which then always gets POST
ed 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
, ...
精彩评论