PHP AJAX Form Validation

Many sites feature web forms to collect information from users. Unfortunately, these forms often provide a poor experience for the user, with predictable results. This article will show you how to make filling out web forms more fun (or at least less painful) for your users with the help of PHP and some AJAX magic.

One of the most important requirements for PHP web forms is usability; it’s the goal of many web designers to improve the user’s experience. With classic PHP web forms, a user is required to enter information in the form and then press the submit button. The PHP script will then validate the data entry to make sure the user has entered the correct information — if it is correct, the user will then be taken to a new page (a success page, for example).

However, things can get a bit uncomfortable in the classic PHP web form when a data entry mistake occurs. If a mistake occurs, PHP will output error messages on the other pages, and the user will be required to type all the information in over and over again. This might be OK for shorter web forms, but it is inefficient for longer web forms (such as a sign up form on large websites where lots of fields are required like the address, phone number, birthday, etc).

The obvious result of this process is a poor user experience. If your web form is not user-friendly, users will avoid your website, and worse, this will affect your sales.

With the use of AJAX, PHP web forms can be made as user friendly as possible. In this article, I will show how to use AJAX technology along with PHP to make user friendly web forms that satisfy the requirements listed below:

1. If a mistake occurs, accurate feedback from the server will be shown to the user, pinpointing where the exact data entry mistake occurred.

2. If a mistake occurs, aside from giving accurate feedback, the user will not need to type in all the fields all over again. This means the page will not be reloaded or refreshed.

3. If there is no mistake or the user successfully enters all the information correctly, the correct information can be shown.

{mospagebreak title=AJAX Validation Process Overview}

AJAX (asynchronous JavaScript and XML) is becoming more popular on the Internet, particularly when used with PHP. Sadly, lots of good PHP books do not include AJAX as a method to help validate user inputs. Therefore, if beginners are relying on good PHP books, they are entirely new to AJAX validation.

A screen shot below differentiates an AJAX and non-AJAX validation process.

Based on the above screen shot, a non-AJAX web form will reload the page to another URL and show the results of the data validation. The user is then required to click the link or press the back button to go back to the form page URL again. At the form page URL, the user will again type all the entries, because they will be lost when reloading the page.

This process is still common on some websites today. It gives a poor user experience because it takes a lot of time just to complete and validate the form.

With AJAX form validation, after clicking the submit button, the validation results (which provide feedback on the data entry mistakes) are still shown in the form URL WITHOUT reloading the page. This is a convenient method that allows the users to easily retype and correct wrong entries.

{mospagebreak title=AJAX Web Form and the Required Files}

Let us make an actual web application. For example, if you are making a web form that can accept the following fields:

  • Full name (first and last names only).
  • Phone numbers (all digits only, no spaces or dashes).
  • Age (all digits only, no spaces). 
  • Spam protection, such as captcha.

We will need this form to be powered by AJAX so that, when the form is submitted to the server, there will be no refresh or page reload.

The first thing we need to do is let PHP start a session which will be needed to pass captcha answers from the original captcha generator PHP file (like captcha.php)

<?php

session_start();

?>

In this article, we will use the prototype AJAX, so we need to append in the <head> tag the JavaScript files needed for AJAX:

<script type="text/javascript" src="prototype.js"></script>

Discussion of the prototype.js is out of the scope of this article. You can read some good references relating to this application. 

The next thing we need is the actual web form.

<form action="ajaxvalidate.php" method="post" onsubmit="return false;">

Enter your Full Name, First name and Last name ONLY (Example: John Doe)<br />

<input style="background-color: #FFFFC0" type="text" name="name" id="name" size="50">

<br /><br />

Enter your Phone number (numbers only, no dashes and spaces)<br />

<input style="background-color: #FFFFC0" type="text" name="phonenumber" id="phonenumber" size="35">

<br /><br />

Enter your Age (Numbers only)<br />

<input style="background-color: #FFFFC0" type="text" name="age" id="age" size="50">

<br /><br />

<img src="captcha.php" />

<br />

Enter the Captcha as shown above:

<br /> <br />

<input style="background-color: #FFFFC0" type="text" name="captcha" id="captcha" size="10">

<br /> <br />

<input type="submit" value="Submit" onClick="sendRequest()">

</form>

The ajaxvalidate.php is the actual PHP script that will process the form inputs. JavaScript executes the sendRequest() function after the user clicks the submit button. The code of this JavaScript function is:

<script type="text/javascript">

function sendRequest() {

new Ajax.Request("ajaxvalidate.php",

{

method: ‘post’,

parameters: ‘name=’+$F(‘name’)+’&phonenumber=’+$F(‘phonenumber’)+’&age=’+$F(‘age’)+’&captcha=’+$F(‘captcha’),

onComplete: showResponse

});

}

function showResponse(req){

$(‘show’).innerHTML= req.responseText;

}

</script>

As you can see, there are four variables to be submitted to the PHP script (name, phone number, age and the user captcha input). The PHP output will then be shown via the showResponse(req)JavaScript function. Any HTML output will be shown with an ID identified as “show” (see show response function code above).

In the web form, this is the actual code:

<p class="yellow" id="show"></p>

The HTML output from PHP will have a background of yellow defined by this style:

<style type="text/css">

P.yellow {background-color: #ffff00;}

</style>

{mospagebreak title=The PHP script to process AJAX inputs}

This is the most important part; this will do the actual validation work. First start session as well as the database connection:

<?php

//start session to recover captcha answers

session_start();

//connect to database

$username = "xxx";

$password = "xxx";

$hostname = "xxx";

$database = "xxx";

$dbhandle = mysql_connect($hostname, $username, $password)

or die("Unable to connect to MySQL");

$selected = mysql_select_db($database,$dbhandle)

or die("Could not select $database");

The form input from AJAX can be retrieve as well as to do input sanitation:

//extract form inputs

$name =$_POST['name'];

$phonenumber =$_POST['phonenumber'];

$age =$_POST['age'];

$usercaptchaanswer =$_POST['captcha'];

$correctcaptcha = $_SESSION['answer'];

//sanitize early for any possible MySQL entry

$name = mysql_real_escape_string(stripslashes(trim($name)));

$phonenumber = mysql_real_escape_string(stripslashes(trim($phonenumber)));

$age = mysql_real_escape_string(stripslashes(trim($age)));

$usercaptchaanswer = mysql_real_escape_string(stripslashes(trim($usercaptchaanswer)));

$correctcaptcha = mysql_real_escape_string(stripslashes(trim($correctcaptcha)));

The first validation will be to see if the captcha is correct:

//Validate captcha entry

if ($correctcaptcha != $usercaptchaanswer) {

echo ‘ERROR: You have entered wrong captcha code';

die ();

}

The next step in the validation is to check for blank fields:

if (empty($name)) {

//name field is blank

echo ‘ERROR: The name field is empty.';

die ();

}

if (empty($phonenumber)) {

//phone field is blank

echo ‘ERROR: The phone field is empty.';

die ();

}

if (empty($age)) {

//age field is blank

echo ‘ERROR: The age field is empty.';

die ();

}

if (empty($usercaptchaanswer)) {

//captcha field is blank

echo ‘ERROR: The captcha field is empty.';

die ();

}

Validating the full name can be tricky, so to make sure only the first name and last name are used, and that valid characters have been entered, the validating script is shown below: 

$mystring = $name;

$findme = ‘ ‘;

$pos = strpos($mystring, $findme);

$actualposition =$pos + 1;

//count strings

$count =strlen($mystring);

//count the number of characters for the first name

$countfirstname = $actualposition – 1;

//count the number of characters for the last name

$countlastname = $count – $actualposition;

//detect if full name has middle name

$posmid= strpos($mystring,$findme,$actualposition) + 1;

$middleadjust = $posmid – $actualposition;

$purealpha = str_replace(" ", "x", $mystring);

if ($actualposition==1) {

echo ‘ERROR: You either forgot your first name or your last name.';

die ();

}

if ($countfirstname <2) {

echo ‘ERROR: You are using an invalid first name, it should contain more than one character.';

die ();

}

if ($countlastname <2) {

echo ‘ERROR: You are using an invalid last name, it should contain more than one character.';

die ();

}

if ($middleadjust >= 2) {

echo ‘ERROR: You should not be using a middle name, please use only first name and last name.';

die ();

}

if (!(ctype_alpha($purealpha))) {

echo ‘ERROR: Full name can only consist of alphabetic characters.';

die ();

}

Finally, to validate the age and phone number:

if (!(ctype_digit($phonenumber))) {

echo ‘ERROR: A phone number should consist of numerical digits only and no spaces between numbers';

die ();

}

//Step 3.3 Validate age

if (!(ctype_digit($age))) {

echo ‘ERROR: Your age should consist of numerical digits only and no spaces between numbers';

die ();

}

You can download and see the actual script.

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye