Ditching that darn javascript form validation

Ok, so I’m yanking out my javascript form validation in favor of something written with php, but a little stumped on how I would do this.

Right now my URL is:

[noparse]http://www.example.com/register.php?action=showForm[/noparse]

I find out what the action is, in this case, showForm. So then the form fields are displayed. When the user clicks submit, it reloads register.php but this time the action=processForm The code then inserts the data into the database. I can use empty() to find out which fields have been left blank, but what would be the best way to reload the page with action=showForm so that the user doesn’t have to re-type all the stuff they just got done typing?

Thanks!

If you have perfectly valid javascript validation code I wouldn’t rip it out completely. I’d keep it in there along with the php code. You see, server side validation is always needed, since users can temper with anything on the client side, or they can have javascript disabled, etc.

However, having javascript validation on the front end does leverage the server a bit in that it can handle some error before the request even gets back to the server.

That being said, what you’d want to do is show the form again to the user, and populate it with values from $_POST, if available.

A usual pattern you see here is


<?php
if (isset($_POST['somefield']))
{
   if (validation()) // validation is a pseudo function here
   {
       save(); // again, a pseudo function
       redirect(); // another pseudo function
   }
}
?>
<html>
  <!-- blah blah blah -->
  <form method="post" action="/register.php?action=showForm">
    <input type="somefield" value="<?php echo isset($_POST['somefield']) ? $_POST['somefield'] : ''; ?>" />
    <input type="submit" value="Go!" />
  </form>
  <!-- blah blah blah -->
</html>

Here I’ve used the existence of $_POST[‘somefield’] as a trigger to do the validation instead of using $_GET[‘action’] because I think the latter is a little less clean, but of course to each their own.
Of course this is a very crude example but it should give you some idea as to how to go about it. If not, feel free to ask questions :slight_smile: