I always had this in mind but never really searched for a good solution or I wasn't determined enough to implement it in my work. When you're used to a certain type and method of working, as a programmer, you're not searching for new cool things and, instead, you tend to use and re-use what you already know. Ever since ajax came out and revolutionized the web and user experience most important I tried to know every little secret of it. Tried all the libraries and cool effects, followed a lot of tutorials and played with many examples but never started a project with ajax on the plan from the very start. In this tutorial we will build a very nice form with ajax posting and validation. Our form will also change the css classes of the inputs, display validation errors and all that sexy stuff which is meant to help our visitor better identify what was filled wrong and what needs to be done in order to successfully submit the form. For this example I decided to use jQuery which is a fantastic, easy to use, javascript library. The form we're using in this tutorial is a simple register form with 4 basic fields: username, password, password again and email address. On form submit we will use ajax to collect the info, send it to a page and analyze the response which is sent back. Also, I've set the onsubmit="return false;" action for the form in order to stay in the same page and take advantage of the beauty of ajax. Let's start with a simple ajax function to submit the form:
function ajax_form(form,site_url,link_id){
var req = jQuery.post
(
site_url,
jQuery('#' + form).serialize(),
function(html){
jQuery('#' + link_id).html(html);
req = null;
}
);
}
This function grabs the submitted form info, send it via post to a given page and injects the response message in some element of choice (div,table,span etc). It needs 3 parameters:
form = the id of the form being submitted
site_url = the url of the page that we're posting at
link_id = the id of the element where you wish to inject the response message (in our case, I placed a div with the id "receiver" just above the form"
Ok. Everything's fine until now when the question comes: how should I perform the validation, how should I point the user to the right place if the validation fails. We need something nice and visual. Every input has a gray border of 1 pixel around it. The input's border where the info was wrong or not filled will become red making it very easy to identify. Needless to say that there are thousands of websites which simply throw an error like "Form validation failed! Please try again" and you're left searching the error in a form of 20 inputs. That's a pain and we're going to solve it from the first step by adding a red border around the those inputs.
The scenario is simple, you submit, the next page receives the data and validates it. If something wrong is found it will be added to an array. For each input in part the validation will either come with an ok or an error in front of the response message. Here's an example:
'error|username|Please fill in your username'
where:
error = the response status for that input
username = the id of the input
Please fill in your username = the response message/validation error
Every response comes in a new line and you can add as many validations you need for a single input. This is very important.
Let's take a look at the validation page:
if ( empty ( $_POST [ 'username' ] ) )
{
$errors [ 'username' ] [] = "Please enter your username\n";
}
if ( empty ( $_POST [ 'password' ] ) )
{
$errors [ 'password' ] [] = "Please enter your password\n";
}
if ( empty ( $_POST [ 'password_confirmed' ] ) )
{
$errors [ 'password_confirmed' ] [] = "Please enter your password again\n";
}
As you can see, in case of an error, the field is represented by an array to hold the messages.
After this, the validation page will do a foreach on the $_POST array (for every input in part) and build the response in order to return html. Each message will be printed on a new line in the response which explains the "\n" sign at the end of the validation message.
It's time to switch back to our javascript code and see how to interpret this type of response. First of all, we will split the response message by the new line.
var explode = html.split("\n");
We now have a javascript array with the validation messages. We will loop through them so that we can identify the inputs with errors.
for ( var i in explode )
{
var explode_again = explode[i].split("|");
}
As you can see, we're using another split in the loop. This one is to identify the id of the input, the type of message and the validation message/instruction.
explode_again[0] = the type of message (error, success)
explode_again[1] = the id of the input
explode_again[2] = the validation message
We're going to extend the loop above and start adding css classes to those inputs:
for ( var i in explode )
{
var explode_again = explode[i].split("|");
jQuery('#' + explode_again[1]).addClass('error');
}
Looking at the css class called .error you will see that it adds the red border mentioned above.
Perfect...but we're not finished. I also want to add a green border to the inputs which passed the validation (this is why the first element in the response message was added). If the visitor enters the right details after failing a submit, we will have to revalidate and assign the right classes to make that input green from red and indicate to the user that the new info fixed the error.
To avoid a conflict between classes or using too much repeating code over and over again we will create a javascript function to add/remove the right classes:
function add_remove_class(search,replace,element_id)
{
if (jQuery('#' + element_id).hasClass(search)){
jQuery('#' + element_id).removeClass(search);
}
jQuery('#' + element_id).addClass(replace);
}
where:
search = the class to be removed
replace = the class to be added
elemeny_id = the input or any other element with an id
The demo contains a little more than what we discussed here but it's enough for you to get started and implement this type of validation.
Demo link | Download link