Link to home
Start Free TrialLog in
Avatar of seraph_matrix_631
seraph_matrix_631Flag for United Kingdom of Great Britain and Northern Ireland

asked on

PHP, JavaScript and Validation!

Hey Experts,
I have been trying to get this page working as it should. I am experimenting with JavaScript to provide better form validation and reduce the requests going to the web server when someone fills out my form and happens to make a mistake.

What i am after:
  1. If JavaScript is enabled i would like the JavaScript function to be run when the user enters the data to the form. This will ensure that there is data in name, email, and password - and that the email is valid and the passwords match.

  2. If JavaScript is disabled, i would like the PHP to take over and process the form as it has been doing.


Problems I am facing:
  1. If i refresh the page the JavaScript loses the data.

  2. If Javascript is enabled it validates the form using JavaScript, but then the PHP takes over even after the form has been validated.

  3. If i enter correct data into the form (Normal Test) the PHP does not process the form.

I have spent HOURS to get this far! My eyes are weary and my Macbook wishes I would give up! So here I am, at a last desperate act to finish this coding!


The Validation script is doing it's job fine. Its mainly an issue with the PHP page, but i cannot seem to pin point the error.


** NOTE: The database connection script is fine and working.
                The mysql username, password, host and database are all working fine  

    I added a H1 tag after the execution of the PHP script on the table and when i submitted the form with all the correct data it showed an empty screen with an empty body in the page source.

==============
Here is the code I am using:
 
The PHP Form (AKA: new_user.php):
=============================
 
<?php 
  session_start(); 
  require('db_conn.php');
  require('lib/http_functions.php');
  
  $db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die ('Connection Error.');
  mysql_select_db(MYSQL_DB, $db) or die (mysql_error($db));
 
  $user_id = (isset($_GET['user_id']) && ctype_digit($_GET['user_id'])) ? $_GET['user_id'] : '';  
  
  $error = "";
?>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Create User</title>
  <link href="css/style1.css" rel="stylesheet" type="text/css" media="screen"/>
  
  <script language="JavaScript" src="js/validate.js"></script>
</head>
 
<body>
<?php if(isset($_POST["action"])) {
 
      $name       = (isset($_POST['$name'])) ? $_POST['$name'] : '';
      $email      = (isset($_POST['$email'])) ? $_POST['$email'] : '';
      $password_1 = (isset($_POST['$password_1'])) ? $_POST['$password_1'] : '';
      $password_2 = (isset($_POST['$password_2'])) ? $_POST['$password_2'] : '';
      $password   = ($password_1 == $password_2) ? $password_1 : '';
      
      if($name="" || empty($name))              { $error = "Name is required!"; } 
      if($email="" || empty($email))            { $error = "Email is required!"; } 
      if($password_1="" || empty($password_1))  { $error = "No password entered!"; } 
      if($password_2="" || empty($password_2))  { $error = "Please confirm your password!"; }
      if($password_1 != $password_2)            { $error = "Passwords don't match!";}
 
      if(!empty($name) && !empty($email) && !empty($password_1))
      {   
         $sql = 'insert into sometable(email, password, name) values ("' . mysql_real_escape_string($email, $db) . '", MD5("' . mysql_real_escape_string($password, $db) . '"), "' . mysql_real_escape_string($name, $db) . '")';
         mysql_query($sql, $db) or die(mysql_error($db));
         echo "<h1>Horrar! Check phpMyAdmin!</h1>";
      } else {
         //echo $error;
      }
} else { ?>
 
    <h2>Create Account v2</h2>
  
    <form name="frmAddUser" action="" method="post" onsubmit="return validate(this)">
      <table id="tblAddUser" border="0" cellpadding="2" cellspacing="2">
        <tr>
          <td>Name:</td>
          <td><input type="text" name="name" id="name" maxlength="20" size="20" value="<?php if(isset($_POST["action"])) { echo $name; } else { echo ""; } ?>"/></td>
        </tr>
        
        <tr>
          <td>Email:</td>
          <td><input type="text" name="email" id="email" maxlength="150" size="35" value="<?php if(isset($_POST["action"])) { echo $email; } else { echo ""; } ?>"/></td>
        </tr>
        
        <?php 
          if(isset($_SESSION['access_level']) && $_SESSION['access_level']==3) 
          {
            echo '<tr><td>Access Level</td>';
            $sql = 'select access_level, access_name from access_levels order by access_level DESC';
            $result = mysql_query($sql, $db)or die(mysql_error($db));
         
            echo '<td>';
            while($row = mysql_fetch_array($result))
            {
              echo '<input type="radio" id="ac1_' . $row['access_level'] . '" name="access_level" value="' . $row['access_level'] . '"';
              if($row['access_level'] == $access_level) { echo ' checked="checked"'; }
              echo '/> <label for="ac1_' . $row['access_level'] . '">' . $row['access_name'] . '</label><br/>'; 
            }
            mysql_free_result($result);
            echo '</td></tr>';
          }
          if(empty($user_id)) {
        ?>
    
        <tr>
          <td><label for="password_1">Password:</label></td>
          <td><input type="password" name="password_1" id="password_1" maxlength="50" value="<?php if(isset($_POST["action"])) { echo $password_1; } else { echo ""; } ?>"/></td>
        </tr>  
    
        <tr>
          <td><label for="password_2">Password (Confirm):</label></td>
          <td><input type="password" name="password_2" id="password_2" maxlength="50" value="<?php if(isset($_POST["action"])) { echo $password_2; } else { echo ""; } ?>"/></td>
        </tr>        
 
        <tr>
          <td colspan="2"><input type="submit" class="submit" name="action" value="Create Account"/></td>
        </tr>
      <?php } else { ?>
        <tr>
          <td>&nbsp;</td>
          <td>
            <input type="hidden" name="user_id" value="<?php echo $user_id; ?>"/>
            <input type="submit" class="submit" name="action" value="Modify Account"/>
          </td>
        </tr>  
      <?php } ?>        
      </table>
    </form>
<?php } ?>  
  </div>
</div>
</body>
</html>
 
 
 
js/validate.js
=========
 
function validate(theForm) {
var reason = "";
 
  reason += validateName(theForm.name);
  reason += validatePassword(theForm.password_1);
  reason += validatePassword(theForm.password_2);
  reason += PasswordMatch(theForm.password_1, theForm.password_2);
  reason += validateEmail(theForm.email);
  
  if (reason != "") {
    alert("Some fields need correction:\n\n" + reason);
    return false;
  }
 
  return true;
}  
 
function PasswordMatch(field1, field2)
{
  var error="";
  if(field1.value != field2.value) {
    field1.style.background = 'yellow';
    field2.style.background = 'yellow';
    error = "Passwords do not match!\n";
  }
  return error;
}
 
 
function validateName(field) {
    var error = ""; 
    if (field.value == "") {
        field.style.background = 'Yellow'; 
        error = "You didn't enter your name.\n";
    } else {
        field.style.background = 'White';
    }
    return error;
}
 
 
 
function validatePassword(field) {
    var error = "";
    var illegalChars = /[\W_]/; // allow only letters and numbers 
 
    if (field.value == "") {
        field.style.background = 'Yellow';
        error = "You didn't enter a password.\n";
    } else if ((field.value.length < 6) || (field.value.length > 15)) {
        error = "The password is the wrong length. \n";
        field.style.background = 'Yellow';
    } else if (illegalChars.test(field.value)) {
        error = "The password contains illegal characters.\n";
        field.style.background = 'Yellow';
    } else {
        field.style.background = 'White';
    }
   return error;
}   
 
 
 
function trim(s)
{
  return s.replace(/^\s+|\s+$/, '');
}
 
function validateEmail(field) {
    var error="";
    var tfield = trim(field.value);                        // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (field.value == "") {
        field.style.background = 'Yellow';
        error = "You didn't enter an email address.\n";
    } else if (!emailFilter.test(tfield)) {              //test email for illegal characters
        field.style.background = 'Yellow';
        error = "Please enter a valid email address.\n";
    } else if (field.value.match(illegalChars)) {
        field.style.background = 'Yellow';
        error = "The email address contains illegal characters.\n";
    } else {
        field.style.background = 'White';
    }
    return error;
}

Open in new window

Avatar of Bobaran98
Bobaran98
Flag of United States of America image

Okay, first off, you've got some mistakes in your PHP conditional statements.  In your code posted above, in lines 37 - 40, you say:

if($variable = "" || other_condition) { }

You should be using a double equals sign rather than just a single equals sign.  Using just one causes it to actually assign the constant value to that variable, the same as if you'd simply typed:

$variable = "";

And since that simple assignment works every time, it's also evaluating as TRUE.  Which means that your code is now behaving as though every one of those variables is blank.

Let me know if that fixes all your problems, or if you encounter more!
As for your JavaScript issues, let me give you my thoughts.

Problem 2 -- disabling the PHP validation -- is the easier to fix, so we'll start there.  I would say add a hidden variable into your form, something like:

<input type="hidden" name="validatedByJS" value=0">

Then, in your JavaScript validation function, when you've checked that everything is fine and you're about to let the form submit... there in the JS you add the following:

document.getElementById('validatedByJS').value = 1;

Then you just check for the value of $_POST['validatedByJS'] in the PHP, and if it's "1", you skip your PHP validation.  Since that form field defaults to 0 and only gets changed if JavaScript is enabled, it meets your needs.

As for losing your form entries when you refresh the page, there are some relatively elaborate solutions, but I'm not sure it's worth it.  I'm thinking you could use AJAX to repeatedly write form field values to your database in case the page gets refreshed; unfortunately, there's no way to detect for the Refresh button being clicked (and therefore no way to do a last minute save only) until the page has been reloaded and all the data's lost.  If AJAX sounds like the way you want to go here, then the question becomes how frequently to run that saving function... every minute?  every time a field changes?  something in-between?

Anyway, if you're interested, let me know.  But don't forget that what you're talking about here is a special bell/whistle.  95% of the people who use the Internet realize that if they click Refresh and lose their form entries, it's their own fault.
Avatar of seraph_matrix_631

ASKER

Thanks!
So far it works but with a few side effects! I tested the JavaScript - That worked without invoking the PHP code.

If I disable JavaScript the PHP kicks in, and the record is added even though i have the PHP validation below.

Is there any way I can have the JavaScript and the PHP output the errors on screen?
JavaScript using document.write($error)


Create User
Name:                [           ]   No Name Entered!
Email:               [           ]   No Email Entered! (or if email entered and invalid show its it's invalid)
Password:            [           ]   No Password Entered!
Password (Confirm):  [           ]   Passwords Don't Match!

                     [ Submit ]


==== Errors ====

Notice: Undefined variable: email in /Users/skulls/Sites/laceytech/new_user.php on line 43

Notice: Undefined variable: password in /Users/skulls/Sites/laceytech/new_user.php on line 43

Notice: Undefined variable: name in /Users/skulls/Sites/laceytech/new_user.php on line 43


phpMyAdmin shows that a record was entered into the users table (it was blank obviously).




==== Code ====
 
  if(isset($_POST['validatedByJS'])==0)  // if form NOT validated by JavaScript
  {
      $name       = (isset($_POST['$name'])) ? $_POST['$name'] : '';
      $email      = (isset($_POST['$email'])) ? $_POST['$email'] : '';
      $password_1 = (isset($_POST['$password_1'])) ? $_POST['$password_1'] : '';
      $password_2 = (isset($_POST['$password_2'])) ? $_POST['$password_2'] : '';
      $password   = ($password_1 == $password_2) ? $password_1 : '';
 
      if($name=="" || empty($name))              { $error = "Name is required!"; } 
      if($email=="" || empty($email))            { $error = "Email is required!"; } 
      if($password_1=="" || empty($password_1))  { $error = "No password entered!"; } 
      if($password_2=="" || empty($password_2))  { $error = "Please confirm your password!"; }
      if($password_1 != $password_2)             { $error = "Passwords don't match!";}
   }   
  
   // This code would be run by default by both JavaScript and PHP if validation is passed!  
     $sql = 'insert into users(email, password, name) values ("' . mysql_real_escape_string($email, $db) . '", MD5("' . mysql_real_escape_string($password, $db) . '"), "' . mysql_real_escape_string($name, $db) . '")';
     mysql_query($sql, $db) or die(mysql_error($db));
  
     echo "<h1>Horrar! Check phpMyAdmin!</h1>";
 
==== Code ====

Open in new window

Well, you just need to add a conditional to your insert statement.  If I may make a few tweaks to your code above:

==== Code ====
 
  $error = ''; //initialize to nothing; stays this way if validated by JS
  if(isset($_POST['validatedByJS'])==0)  // if form NOT validated by JavaScript
  {
      $name       = (isset($_POST['$name'])) ? $_POST['$name'] : '';
      $email      = (isset($_POST['$email'])) ? $_POST['$email'] : '';
      $password_1 = (isset($_POST['$password_1'])) ? $_POST['$password_1'] : '';
      $password_2 = (isset($_POST['$password_2'])) ? $_POST['$password_2'] : '';
      $password   = ($password_1 == $password_2) ? $password_1 : '';
 
      if($name=="" || empty($name))              { $error = "Name is required!"; } 
      if($email=="" || empty($email))            { $error = "Email is required!"; } 
      if($password_1=="" || empty($password_1))  { $error = "No password entered!"; } 
      if($password_2=="" || empty($password_2))  { $error = "Please confirm your password!"; }
      if($password_1 != $password_2)             { $error = "Passwords don't match!";}
   }   
  
   // This code would be run by default by both JavaScript and PHP if validation is passed!  
  if($error = "") {
     $sql = 'insert into users(email, password, name) values ("' . mysql_real_escape_string($email, $db) . '", MD5("' . mysql_real_escape_string($password, $db) . '"), "' . mysql_real_escape_string($name, $db) . '")';
     mysql_query($sql, $db) or die(mysql_error($db));
  }
 
     echo "<h1>Horrar! Check phpMyAdmin!</h1>";
 
==== Code ====

Open in new window

As for your error message... when it comes to a form submission like you're doing, where you're using validation, I like to have the form submit to the same page.  That way if you do PHP validation and it fails, you can automatically repopulate the form fields with whatever values they already typed, then pop up a JavaScript alert window.

Obviously, if the validation happens (and fails) in the JavaScript, the alert window is easy.  You just create your error message, then

var error = "You forgot to tell us your name!";
window.alert(error);

With the PHP validation, you can leave everything the way your code is above.  Then, at the very bottom of the page, right before the </BODY> tag, put:

<?php if($error <> "") { ?>
<script language="javascript1.2">
window.alert("<?php echo $error; ?>");
</script>
<?php } ?>

Of course, with this latter example, you just have to make sure you don't use any quotation marks in your $error string... or if you do, make sure you escape them first, e.g.

$error = "You made a \"mistake\" on your form entry!";

Finally, the reason you put this code at the very bottom of the page is that when that alert window pops up, the page load freezes until the user hits OK.  And if it freezes midway, it (a) looks unprofessional and (b) prevents the user from actually looking at those fields s/he screwed up on.
Let me make one more comment, totally unasked for. :-)  When it comes to validation and error messages, I like to do something like in the code below.

Note that adding a \n in an alert window creates a new line, while \t creates a tab indent.  So this method below allows you to give a list of all validation errors, formatted in an easy to read fashion.  In my code below, I've added another slash to make each  \n a \\n and each \t a \\t, because one slash will get stripped out of each instance when it's written onto the page (the same way it is if you use it in front of a quotation mark).

As things stand in your PHP code above, only the last error detected will be shown to the user (new values keep getting assigned over top of $error rather than concatenated).  If a user has multiple errors, they'll keep hitting submit and keep getting a different error.

You can, of course, do something similar to below in your JavaScript validation as well.

<?php
 
	$error = "";
 
	if($name=="" || empty($name))              { $error .= "\\n\\t- Name is required!"; } 
	if($email=="" || empty($email))            { $error .= "\\n\\t- Email is required!"; } 
	if($password_1=="" || empty($password_1))  { $error .= "\\n\\t- No password entered!"; } 
	if($password_2=="" || empty($password_2))  { $error .= "\\n\\t- Please confirm your password!"; }
 
	if($error <> "") {
		$error = "Please correct the following errors:" . $error;
	}
 
?>

Open in new window

I don't know what I am doing wrong here but i add the code (thank you for the out errors section! :-D )
When i click submit (all blank fields) I get a blank screen, nothing output.

If i add some data to the form, click submit then go back the data entered is wiped out!


Despite having this on the input controls:
   value="<?php if(isset($_POST["action"])) { echo $name; } else { echo ""; } ?>
Code used below on new_user.php
<body>
<?php if(isset($_POST["action"])) 
{
  if(isset($_POST['validatedByJS'])==0)  // if form NOT validated by JavaScript
  {
      $name       = (isset($_POST['$name'])) ? $_POST['$name'] : '';
      $email      = (isset($_POST['$email'])) ? $_POST['$email'] : '';
      $password_1 = (isset($_POST['$password_1'])) ? $_POST['$password_1'] : '';
      $password_2 = (isset($_POST['$password_2'])) ? $_POST['$password_2'] : '';
      $password   = ($password_1 == $password_2) ? $password_1 : '';
 
      $error="";
	  if($name=="" || empty($name))              { $error .= "\\n\\t- Name is required!"; } 
	  if($email=="" || empty($email))            { $error .= "\\n\\t- Email is required!"; } 
	  if($password_1=="" || empty($password_1))  { $error .= "\\n\\t- No password entered!"; } 
	  if($password_2=="" || empty($password_2))  { $error .= "\\n\\t- Please confirm your password!"; }
      if($password_1 != $password_2)             { $error .= "\\n\\t- Passwords don't match!"; }
      
      if($error <> "") {
        $error = "Please correct the following errors:" . $error;
	  }  
  }  // End PHP Validation Routine --!
   
  if($error="")    // This code would be run by default by both JavaScript and PHP if validation is passed!  
  {
     $sql = 'insert into users(email, password, name) values ("' . mysql_real_escape_string($email, $db) . '", MD5("' . mysql_real_escape_string($password, $db) . '"), "' . mysql_real_escape_string($name, $db) . '")';
     mysql_query($sql, $db) or die(mysql_error($db));
     echo "<h1>Sign-up Complete!</h1><br><p>Welcome to LaceyTechSolutions!</p>";
  }
   
} else { ?>
 
    <h2>Create Account v3</h2>

Open in new window

Ok, consider your cases.  You've got one situation in which the page would come back blank-- if you submit and the PHP validation finds errors, you're assigning that message to $error just fine... but you're never outputting $error!  Take a look at lines 19-21.

Of course, you can sometimes get a blank screen if you've got parse issues with your PHP, but that's probably not the case here.  (let me know if it is, though!)
I'm still getting errors but my brain is wiped!
Its 2.44am and I'm going to go to bed.

Maybe I will find out why it's not outputting the errors (Even tho i've added echo $errors; afterwards).

Its strange because even using JavaScript it's not grabbing the submitted variables! which seems insane because as you can see i'm assigning a variable to get the posted data from the form!  $variable =  $_POST['fieldname'];

Ok, try one last thing before you go to bed, then... if I'm not too late!  At the very top of your script, put in the following code in order to list out all variable names and associated values that have been submitted in the form.  It should show you exactly what you're getting!

If you'd prefer, you can print the $_POST array instead of $_REQUEST, but I prefer to always use $_REQUEST so I don't accidentally get confused between post and get variables.

<body>
<?php if(isset($_POST["action"])) 
{
    echo "<pre>";
    print_r($_REQUEST);
    echo "</pre><p>";
 
    // and then everything else can stay
 
?>

Open in new window

Result of the PHP Validation (Javascript was disabled)

Array
(
    [name] => test
    [email] => test@domain.com
    [password_1] => 123456
    [password_2] => 123456
    [action] => Create Account
    [validatedByJS] => 0
    [PHPSESSID] => 7513bac5ef15af0ac9adc78490c5b5a6
)


Notice: Undefined variable: email in /Users/skulls/Sites/laceytech/new_user.php on line 55

Notice: Undefined variable: password in /Users/skulls/Sites/laceytech/new_user.php on line 55

Notice: Undefined variable: name in /Users/skulls/Sites/laceytech/new_user.php on line 55


Line 55 is the database SQL Statement.
So it's passing the if(!$error) and trying to run the SQL, it inserts a blank record because the variable is apparently undefined for email, name and password.


... Wait ...
I've just realized that i needed the $_REQUEST variable assignment's to be right at the very top of the page!


=====
<?php
  session_start();
 
  $db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die ('Connection Error.');
  mysql_select_db(MYSQL_DB, $db) or die (mysql_error($db));
 
  $user_id = (isset($_GET['user_id']) && ctype_digit($_GET['user_id'])) ? $_GET['user_id'] : '';  
  $error = "";
 
  $name       = (isset($_REQUEST['name'])) ? $_REQUEST['name'] : '';
  $email      = (isset($_REQUEST['email'])) ? $_REQUEST['email'] : '';
  $password_1 = (isset($_REQUEST['password_1'])) ? $_REQUEST['password_1'] : '';
  $password_2 = (isset($_REQUEST['password_2'])) ? $_REQUEST['password_2'] : '';
  $password   = ($password_1 == $password_2) ? $password_1 : '';  
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


  Create User
=====


It would seem i'm still not able to see any errors generated by PHP!
Why is this not working:

==== Code ====
<?php if(isset($_POST["action"]))
{
  if(isset($_POST['validatedByJS'])==0)  // if form NOT validated by JavaScript
  {
        if(empty($name))              { $error .= "\\n\\t- Name is required!"; }
        if(empty($email))            { $error .= "\\n\\t- Email is required!"; }
        if(empty($password_1))  { $error .= "\\n\\t- No password entered!"; }
        if(empty($password_2))  { $error .= "\\n\\t- Please confirm your password!"; }
      if($password_1 != $password_2)             { $error .= "\\n\\t- Passwords don't match!"; }
     
      if($error <> "") {
        $error = "Please correct the following errors:" . $error;
        }
        echo $error;  // output the errors on screen!
        
  }  // End PHP Validation Routine --!
   
  if(!$error)    // This code would be run by default by both JavaScript and PHP if validation is passed!  
  {
     $sql = 'insert into users(email, password, name) values ("' . mysql_real_escape_string($email, $db) . '", MD5("' . mysql_real_escape_string($password, $db) . '"), "' . mysql_real_escape_string($name, $db) . '")';
     mysql_query($sql, $db) or die(mysql_error($db));
  }
==== Code ====  
Try running the page again, but with one change... at the bottom of what you just posted, comment out where you execute the query and instead just echo the query statement to the page:

     echo "<p>" . $sql . "<p>";
     //mysql_query($sql, $db) or die(mysql_error($db));

That should tell you exactly what you're TRYING to execute! :-)
If you're indeed not getting the right values into the INSERT statement, your next bet is to remove each instance of the mysql_real_escape_string() function call... at least for testing.  See if it works when you send the variables directly... because after all, the variables must be fine if you've even gotten to that point in your code!

One other possibility... I can't remember if this is true for MySQL, but I know MS SQL refuses to acknowledge quotation marks as a string indicator-- it will only accept apostrophes (at least in my installation).

So if you wanted to test both of these possibilities at once, you could try one or both of the following:


$sql = "insert into users (email, password, name) values ('$email', '$password', '$name')";
 
$sql = "insert into users (email, password, name) values ('$email', MD5('$password'), '$name')";

Open in new window

this is really pissing me off now!
The PHP validation doesn't work!!

The javascript validation is sound and works as i need it to, but if javacript is disabled and i press "add user" it adds a blank record bypassing all validation!!

i would preferably like the errors to be shown on the same page as the form (not a blank / new page)


so i added <tr> <td> <?php echo $error; ?> </td>
and i cannot see any of the errors generated!  


This is really annoying me now!!
I have been trying to get it to work for ages now! I did what you aid above and the SQL IS getting the right data from the PHP, so that's one less thing to worry about.
LOL.  You remember what we talked about early, about using a single equals sign in your conditional check?  Take a look at the code where you check to see whether $error is blank... See, so once again, validation is being flouted and values added to the database no matter what. :-)

So does that take care of everything?
done some testing...

using the code above to change the validated by JS value to 1 does not work using the line you have given above.

used an alert box at the end of the validation checks (JavaScript) and viewed the page source.
<input type="hidden" name="validatedByJS" id="validatedByJS" value="0">


Neither php or javascript validation works now.
and no data is inserted into the database table.
and the form goes back to itself with all fields cleared.
Can you post the entire code as it currently stands?  Did you fix the double-equals-sign issue on the conditional for writing to the database?  Also, with your JavaScript validation, realize that some function calls-- such as getElementById-- are case sensitive.  (I can't tell you how many times I've used getElementByID rather than getElementById and spent forever going line by line looking for my problem!)

But yeah, post everything and don't lose hope!  We were close just "moments" ago, and you had the JavaScript/PHP validation trade-off nearly working.  We'll get it. :-)
JavaScript File:function validate(theForm) {
var reason = "";
 
  reason += validateName(theForm.name);
  reason += validateEmail(theForm.email);
  reason += validatePassword(theForm.password_1);
  reason += validatePassword(theForm.password_2);
  reason += PasswordMatch(theForm.password_1, theForm.password_2);
 
  if (reason != "") {
    alert("Some fields need correction:\n\n" + reason);
    return false;
  }
 
 document.getElementById('validatedByJS').value = 1;  alert(document.getElementById('validatedByJS').value);
  // Alert returns 0, if i use == 1 it also returns 0
  // checked the input on the form and it has a name and id of validatedByJS

 return true;
}  
 
function PasswordMatch(field1, field2)
{
  var error="";
  if(field1.value != field2.value) {
    field1.style.background = 'yellow';
    field2.style.background = 'yellow';
    error = "Passwords do not match!\n";
  }
  return error;
}
 
 
function validateName(field) {
    var error = "";
    if (field.value == "") {
        field.style.background = 'Yellow';
        error = "You didn't enter your name.\n";
    } else {
        field.style.background = 'White';
    }
    return error;
}
 
 
 
function validatePassword(field) {
    var error = "";
    var illegalChars = /[\W_]/; // allow only letters and numbers
 
    if (field.value == "") {
        field.style.background = 'Yellow';
        error = "You didn't enter a password.\n";
    } else if ((field.value.length < 6) || (field.value.length > 15)) {
        error = "The password is the wrong length. \n";
        field.style.background = 'Yellow';
    } else if (illegalChars.test(field.value)) {
        error = "The password contains illegal characters.\n";
        field.style.background = 'Yellow';
    } else {
        field.style.background = 'White';
    }
   return error;
}  
 
 
 
function trim(s)
{
  return s.replace(/^\s+|\s+$/, '');
}
 
function validateEmail(field) {
    var error="";
    var tfield = trim(field.value);                        // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (field.value == "") {
        field.style.background = 'Yellow';
        error = "You didn't enter an email address.\n";
    } else if (!emailFilter.test(tfield)) {              //test email for illegal characters
        field.style.background = 'Yellow';
        error = "Please enter a valid email address.\n";
    } else if (field.value.match(illegalChars)) {
        field.style.background = 'Yellow';
        error = "The email address contains illegal characters.\n";
    } else {
        field.style.background = 'White';
    }
    return error;
}



PHP Code:
<?php
  session_start();
  require('db_conn.php');
  require('lib/http_functions.php');
  require('lib/general_functions.php');
 
  $db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die ('Connection Error.');
  mysql_select_db(MYSQL_DB, $db) or die (mysql_error($db));
 
  $user_id = (isset($_GET['user_id']) && ctype_digit($_GET['user_id'])) ? $_GET['user_id'] : '';  
  $error = "";
 
  $name       = (isset($_REQUEST['name'])) ? $_REQUEST['name'] : '';
  $email      = (isset($_REQUEST['email'])) ? $_REQUEST['email'] : '';
  $password_1 = (isset($_REQUEST['password_1'])) ? $_REQUEST['password_1'] : '';
  $password_2 = (isset($_REQUEST['password_2'])) ? $_REQUEST['password_2'] : '';
  $password   = ($password_1 == $password_2) ? $password_1 : '';  
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Create User</title>
  <link href="css/style1.css" rel="stylesheet" type="text/css" media="screen"/>
 
  <script language="JavaScript" src="js/validate.js"></script>
</head>

<body>
<?php if(isset($_POST["action"]))
{
  if(isset($_POST['validatedByJS'])==0)  // if form NOT validated by JavaScript
  {
      if(empty($name))                { $error = "\\n\\t- Name is required!"; }
      if(empty($email))               { $error .= "\\n\\t- Email is required!"; }
      if(empty($password_1))          { $error .= "\\n\\t- No password entered!"; }
      if(empty($password_2))          { $error .= "\\n\\t- Please confirm your password!"; }
      if($password_1 != $password_2)  { $error .= "\\n\\t- Passwords don't match!"; }
     
      if($error <> "") { $error = "Please correct the following errors:" . $error; }  
  }
   
  if(!$error)    // This code would be run by default by both JavaScript and PHP if validation is passed!  
  {
     $sql = 'insert into users(email, password, name) values ("' . mysql_real_escape_string($email, $db) . '", MD5("' . mysql_real_escape_string($password, $db) . '"), "' . mysql_real_escape_string($name, $db) . '")';
     mysql_query($sql, $db) or die(mysql_error($db));
     redirect('login.php');
  }
 
 
} else { ?>
 
    <h2>Create Account v6</h2>
    <form name="frmAddUser" action="" method="get" onsubmit="return validate(this)">
      <table id="tblAddUser" border="0" cellpadding="2" cellspacing="2">
        <tr>
          <td colspan="2"><?php echo $error; ?></td>
        </tr>
       
        <tr>
          <td>Name:</td>
          <td><input type="text" name="name" id="name" maxlength="20" size="20" value="<?php if(isset($_POST["action"])) { echo $name; } ?>"/></td>
        </tr>
       
        <tr>
          <td>Email:</td>
          <td><input type="text" name="email" id="email" maxlength="150" size="35" value="<?php if(isset($_POST["action"])) { echo $email; } ?>"/></td>
        </tr>
       
        <?php
          if(isset($_SESSION['access_level']) && $_SESSION['access_level']==3)
          {
            echo '<tr><td>Access Level</td>';
            $sql = 'select access_level, access_name from access_levels order by access_level DESC';
            $result = mysql_query($sql, $db)or die(mysql_error($db));
         
            echo '<td>';
            while($row = mysql_fetch_array($result))
            {
              echo '<input type="radio" id="ac1_' . $row['access_level'] . '" name="access_level" value="' . $row['access_level'] . '"';
              if($row['access_level'] == $access_level) { eacho ' checked="checked"'; }
              echo '/> <label for="ac1_' . $row['access_level'] . '">' . $row['access_name'] . '</label><br/>';
            }
            mysql_free_result($result);
            echo '</td></tr>';
          }
          if(empty($user_id)) {
        ?>
   
        <tr>
          <td><label for="password_1">Password:</label></td>
          <td><input type="password" name="password_1" id="password_1" maxlength="50" value="<?php if(isset($_POST["action"])) { echo $password_1; } else { echo ""; } ?>"/></td>
        </tr>  
   
        <tr>
          <td><label for="password_2">Password (Confirm):</label></td>
          <td><input type="password" name="password_2" id="password_2" maxlength="50" value="<?php if(isset($_POST["action"])) { echo $password_2; } else { echo ""; } ?>"/></td>
        </tr>        

        <tr>
          <td colspan="2">
            <input type="submit" class="submit" name="action" value="Create Account"/></td>
            <input type="hidden" name="validatedByJS" id="validatedByJS" value="0">  <!-- value=0 indicates it was validated by PHP -->
        </tr>
      <?php } else { ?>
        <tr>
          <td>&nbsp;</td>
          <td>
            <input type="hidden" name="user_id" value="<?php echo $user_id; ?>"/>
            <input type="submit" class="submit" name="action" value="Modify Account"/>
          </td>
        </tr>  
      <?php } ?>        
      </table>
    </form>
<?php } ?>  
  </div>
</div>

</body>
</html>

This is what i have now, so we both know what code is current and can try and work on it
Your JavaScript looks ok in regard to validating and then changing the value of validatedByJS to 1.  Can you confirm that it was working properly before?  I'm pretty sure you said it was.  If that's the case, something's changed...  Do you know for sure you don't have some other JavaScript error causing problems?  If, for example, any one of your validation function calls generated an error, it could result in odd execution later.  I don't know, though...

One thought would be to try assigning it the string value of "1" rather than the integer value of 1, since those form variables only pass strings anyway.  But if it worked before, I don't see why that should make a difference now...

Another thing I would suggest in general is to simplify, simplify, simplify.  Each time you use your PHP variables, you're being very careful not to print an undeclared variable.  And that's admirable!  However, look at the very top of your PHP code.  After you execute this:

 $name       = (isset($_REQUEST['name'])) ? $_REQUEST['name'] : '';
  $email      = (isset($_REQUEST['email'])) ? $_REQUEST['email'] : '';
  $password_1 = (isset($_REQUEST['password_1'])) ? $_REQUEST['password_1'] : '';
  $password_2 = (isset($_REQUEST['password_2'])) ? $_REQUEST['password_2'] : '';
  $password   = ($password_1 == $password_2) ? $password_1 : '';  
... all five of those variables are guaranteed to have a string value (even if it's blank).  From that point forward, you should never have to call isset() again.  Furthermore, when it comes to echoing those variables as initial values for form fields, you don't need to use any conditionals.  Instead of...

<input type="password" name="password_1" id="password_1" maxlength="50" value="<?php if(isset($_POST["action"])) { echo $password_1; } else { echo ""; } ?>"/>
... just put...

<input type="password" name="password_1" id="password_1" maxlength="50" value="<?php echo $password_1;} ?>"/>

... because remember, by this point $password_1 is always a string, and if it's blank, well, then it will print nothing for the default value.  And that includes if the form wasn't submitted, so there's no reason to check that action.

Cleaning all this up probably won't do anything for our JavaScript problem, but it'll certainly make the code a bit easier to read and, as general practice goes, help protect you from the errors that inevitable come from unnecessary complexity.
OK done that ..
Now it seems we're getting somewhere.

If I blank out all the fields and press OK JavaScript validation kicks in...

However. If i press F5 or press the submit button the form defaults name to 1 and password_1 to a dot (so  character or number is in there)



if i fill out the form (valid entries) with Javascript enabled (not all the validation is being caried out and is nto allowing for un-authorized values) then click add user, it return a value or 1 from the alert line in the javascript validation script, resets the form to name = 1, password_1 = some character (1 dot visible) but does not add the record of data.


this is so efuriating!
i know once i get this page done im sure to be able to setup the other pages fine, but so many errors!! ahhhhh! --- or lack of in this case!


thank you so so much for dedicating your time to helping me solve this!!
Im very grateful!
I'm actually trying to run your code now for the first time.  I'll let you know how that goes.  But in the meantime... did you realize you're calling eacho in your PHP code at one point rather than echo? :-)  It's right below the email form field.
yeah i noticed that and corrected it :)
Okay, I've got your code running great. :-)  You've just got two silly errors you need to fix.

(1) At some point, you switched your form to a GET action rather than POST, but some of your PHP is looking for POST.  That's why the PHP validation won't work.  My suggestion is replace all $_POST in your code with $_REQUEST, and then also replace all $_GET with $_REQUEST.  $_REQUEST encompasses both, which is why I mentioned earlier that I like to use it to avoid silly errors (like this one).

(2) Even then, though, your PHP validation won't work quite right, because you've got...

 if(isset($_POST['validatedByJS'])==0)
... in your PHP validation conditional, when it should be...

 if(isset($_REQUEST['validatedByJS']) && $_REQUEST['validatedByJS']=="0")
Note that the second condition (the one that checks the value) won't be evaluated unless the first condition (isset()) evaluates true.

Fix these items, and you should be good to go!  It works great for me!

I am so getting annoyed with the post comment box on this site! It won't work properly if JavaScript is disabled, so when i paste in an entry from my code it deletes the whole of what i have typed and i cannot undo the action! Gaaah!!.

Anyways! [Third time of retyping this same fecking post!!]

If JavaScript is enabled and errors are on form, validation is A-OK!
When i submit with JavaScript enabled, it inserts the record, the email is set to 1 (don't know why!) and it returns "Duplicate entry '1' for key 2".


If JavaScript is disabled i type in my data with an error and it seems to skip the PHP validation and go straight to inserting the record and fails. It shows the same error as above. No data is added to the database under PHP only mode.

Even if i use a different email address in the form it doesn't like it and shows the same Duplicate '1' for field 2 error.


The URL is:
http://localhost/site/new_user.php?name=test&email=test%40test.com&password_1=111111&password_2=111222&action=Create+Account&validatedByJS=0

So the email data is being sent.
Could you post up your file that you have working? Might be easier! LOL
ASKER CERTIFIED SOLUTION
Avatar of Bobaran98
Bobaran98
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
OK
It's working to an extent.
But even though the data being sent from the form to the
Output if JavaScript is DISABLED and the form meets all requirements:

Array
(
    [name] => ben
    [email] => ben@ntlworld.com
    [password_1] => 333333
    [password_2] => 333333
    [action] => Create Account
    [validatedByJS] => 0
    [PHPSESSID] => 7513bac5ef15af0ac9adc78490c5b5a6
)
 

Errors: Duplicate entry '1' for key 2
Okay, look, whatever you've got going on here, it's obvious you've got additional code that you've not shown me-- additional validation code, perhaps?  If you run the page exactly like I posted it above, there's no possible way for the $error variable to end up with a value like "Duplicate entry..."  So if you're getting that, your problem has to be somewhere in the code you've not shown me.

If you run the exact same input above (ben/ben@ntlworld.com/333333) in the page as I listed it in my last post, you should get the following output:

Array
(
    [name] => ben
    [email] => ben@ntlworld.com
    [password_1] => 333333
    [password_2] => 333333
    [action] => Create Account
    [validatedByJS] => 0
)
Errors:

insert into users(email, password, name) values ("ben@ntlworld.com", MD5("333333"), "ben")

And of course, nothing is listed after Errors:, which means no error was generated.
OK i have got it working!
I will need to back this file up and then add more PHP validation to it.

Thank you for your help!
Very nice Expert.
Well mannered and willing to help. Everything was explained well and professionally.

Thank you very much!
My pleasure!