We are going to learn from this tutorial how to create a form that will process using AJAX and PHP. Based on mootools as a javascript library and for the AJAX effect, our form will call the php page in order to process and validate our inputs. From here the title which represents the whole above definition: AJAX form validation.
Our example is supposed to be a registration page. It will do nothing after validation but show errors or a success message. If you wish to combine it and really create a registration page with email activation, membership, login page, forgot password, mysql tables and all that stuff please read the PHP login tutorial as well.
The form will be a simple one pointing to register.php in our case without redirecting or refreshing the page on submit thanks to mootools and will use a div (<div id=”log”>) to communicate with the visitor by showing error or success messages upon validation. Thanks to Fx.Styles we’re able to display a loading spinner by modifying the css property of our div until we receive a response from the php page (register) which is supposed to take care of the validation.
window.addEvent('domready', function(){ $('registerForm').addEvent('submit', function(e) { new Event(e).stop(); var log = $('log_res').empty().addClass('ajax-loading'); this.send({ update: log, onComplete: function() { log.removeClass('ajax-loading'); } }); }); });
Looking at the Javascript code above you will notice a very important thing that we can use with mootools. The domready event which is way more faster than the old window onload. The form is ready to validate using AJAX in no time and all that I’ve mentioned above sits on a 23kb js file. That’s a great tool to play with if you ask me.
Let’s move to the php file where the main “engine” sits. Our validation will be simple, we will check if the required data (all of them are required in our case) is not empty, if the two passwords match one another and if the visitor provided a valid email address.
<?php include('functions.php'); if ($_POST['First_name']=='' || strlen($_POST['First_name'])<3) { $errors[] = 'First name is required and must contain 3 characters or more'; } if ($_POST['Last_name']=='' || strlen($_POST['Last_name'])<3) { $errors[] = 'Last name is required and must contain 3 characters or more'; } if ($_POST['Username']=='' || alpha_numeric($_POST['Username'])==FALSE) { $errors[] = 'Username is required and must be alpha-numeric'; } if ($_POST['Password']=='' || alpha_numeric($_POST['Password'])==FALSE) { $errors[] = 'A password is required and must be alpha-numeric'; } if ($_POST['Password']!=$_POST['re_Password']) { $errors[] = 'The two passwords must match'; } if (valid_email($_POST['Email'])==FALSE) { $errors[] = 'Please supply a valid email address'; } if(is_array($errors)) { echo '<p class="error"><b>The following errors occured</b></p>'; while (list($key,$value) = each($errors)) { echo '<span class="error">'.$value.'</span><br />'; } } else { //do something here----store to db, send email echo '<p><b>Success!</b></p>'; echo '<span>Your registration was successfully processed. You may login and start using your account. Thank you for registering !</span>'; } ?>
This is pretty usual and easy even for real beginners. The important thing in our validation process is how we build and display the error messages. Using if, elseif and else you’re able to achieve something similar only that (in case we have more than 1 error) the messages will be displayed one at a time. As you can see, I’ve used only if statements and each time one of them finds a mismatch or an error adds a value to the array $errors[].
The last statement checks if we have an array (since the array $errors[] can be defined only if we have an error). In case the result is yes, we perform a loop to display all of them on different lines:
while (list($key,$value) = each($errors)) { echo '<span class="error">'.$value.'</span><br />'; }
In case not, there’s no need for a loop since we can show a success message in only one case (if everything passed our ajax validation). I’ve added a comment there (//do something here—-store to db, send email), it’s the place where you should place your code for storing the info to the database, sending confirmation emails etc.
Here’s a demo of our application at work (download link lower on the page). Enjoy!