SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Guru
    Join Date
    Sep 2004
    Provo, UT
    1 Post(s)
    0 Thread(s)

    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:

    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?

    Last edited by ScallioXTX; May 27, 2011 at 15:56. Reason: delinkified example url
    Convert your dollars into silver coins.

  2. #2
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    The Netherlands
    153 Post(s)
    2 Thread(s)
    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 Code:
    if (isset($_POST['somefield']))
       if (
    validation()) // validation is a pseudo function here
    save(); // again, a pseudo function
    redirect(); // another pseudo function
      <!-- 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!" />
      <!-- blah blah blah -->
    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
    Rémon - Hosting Advisor

    SitePoint forums will switch to Discourse soon! Make sure you're ready for it!

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts