AJAX (Asynchronous JavaScript and XML) is the art of exchanging data with a server, and updating parts of a web page – without reloading the whole page. Therefore, Ajax makes web page quick responsive.
We have already explained about form validation using different technologies. Now, the same can be done by using Ajax, In this blog post we will tell you how it can be done.
We have created an HTML form with four input fields and validation of each field is done by using combine logic of Ajax, PHP and Javascript.
We have used The onreadystatechange Event of Ajax in our javascript file. All you have to do is just follow our codes or download it to use.
HTML File: index.html
Here, we create our form
<!DOCTYPE html>
<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="script.js"></script>
</head>
<body>
<div id="mainform">
<div class="innerdiv">
<!-- Required Div Starts Here -->
<h2>Form Validation Using AJAX</h2>
<form action='#' id="myForm" method='post' name="myForm">
<h3>Fill Your Information!</h3>
<table>
<tr>
<td>Username</td>
<td><input id='username1' name='username' onblur="validate('username', this.value)" type='text'></td>
<td>
<div id='username'></div>
</td>
</tr>
<tr>
<td>Password</td>
<td><input id='password1' name='password' onblur="validate('password', this.value)" type='password'></td>
<td>
<div id='password'></div>
</td>
</tr>
<tr>
<td>Email</td>
<td><input id='email1' name='email' onblur="validate('email', this.value)" type='text'></td>
<td>
<div id='email'></div>
</td>
</tr>
<tr>
<td>website</td>
<td><input id='website1' name='website' onblur="validate('website', this.value)" type='text'></td>
<td>
<div id='website'></div>
</td>
</tr>
</table>
<input onclick="checkForm()" type='button' value='Submit'>
</form>
</div>
</body>
</html>
PHP File: validation.php
In this php script Regular Expression is used for validation.
<?php
$value = $_GET['query'];
$formfield = $_GET['field'];
// Check Valid or Invalid user name when user enters user name in username input field.
if ($formfield == "username") {
if (strlen($value) < 4) {
echo "Must be 3+ letters";
} else {
echo "<span>Valid</span>";
}
}
// Check Valid or Invalid password when user enters password in password input field.
if ($formfield == "password") {
if (strlen($value) < 6) {
echo "Password too short";
} else {
echo "<span>Strong</span>";
}
}
// Check Valid or Invalid email when user enters email in email input field.
if ($formfield == "email") {
if (!preg_match("/([w-]+@[w-]+.[w-]+)/", $value)) {
echo "Invalid email";
} else {
echo "<span>Valid</span>";
}
}
// Check Valid or Invalid website address when user enters website address in website input field.
if ($formfield == "website") {
if (!preg_match("/b(?:(?:https?|ftp)://|www.)[-a-z0-9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|]/i", $value)) {
echo "Invalid website";
} else {
echo "<span>Valid</span>";
}
}
?>
JAVASCRIPT File: script.js
javascript file consist of ajax functionality.
function checkForm() {
// Fetching values from all input fields and storing them in variables.
var name = document.getElementById("username1").value;
var password = document.getElementById("password1").value;
var email = document.getElementById("email1").value;
var website = document.getElementById("website1").value;
//Check input Fields Should not be blanks.
if (name == '' || password == '' || email == '' || website == '') {
alert("Fill All Fields");
} else {
//Notifying error fields
var username1 = document.getElementById("username");
var password1 = document.getElementById("password");
var email1 = document.getElementById("email");
var website1 = document.getElementById("website");
//Check All Values/Informations Filled by User are Valid Or Not.If All Fields Are invalid Then Generate alert.
if (username1.innerHTML == 'Must be 3+ letters' || password1.innerHTML == 'Password too short' || email1.innerHTML == 'Invalid email' || website1.innerHTML == 'Invalid website') {
alert("Fill Valid Information");
} else {
//Submit Form When All values are valid.
document.getElementById("myForm").submit();
}
}
}
// AJAX code to check input field values when onblur event triggerd.
function validate(field, query) {
var xmlhttp;
if (window.XMLHttpRequest) { // for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState != 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = "Validating..";
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = xmlhttp.responseText;
} else {
document.getElementById(field).innerHTML = "Error Occurred. <a href='index.php'>Reload Or Try Again</a> the page.";
}
}
xmlhttp.open("GET", "validation.php?field=" + field + "&query=" + query, false);
xmlhttp.send();
}
CSS File: style.css
Styling HTML Elements.
@import "http://fonts.googleapis.com/css?family=Fauna+One|Muli";
#mainform{
width:960px;
margin:20px auto;
padding-top:20px;
font-family:'Fauna One',serif
}
#mainform h2{
width:100%;
float:left;
text-align:center;
margin-top:35px
}
.innerdiv{
width:65%;
float:left
}
form{
background-color:#fff;
color:#123456;
box-shadow:0 1px 1px 1px gray;
width:500px;
margin:50px 250px 0 50px;
float:left;
height:400px;
padding:10px
}
h3{
margin-top:0;
color:#fff;
background-color:#0B87AA;
text-align:center;
width:100%;
height:50px;
padding-top:30px
}
input{
width:250px;
height:30px;
margin-top:10px;
border-radius:3px;
padding:2px;
box-shadow:0 1px 1px 0 #a9a9a9;
margin:10px
}
input[type=button]{
background-color:#0B87AA;
border:1px solid #fff;
font-family:'Fauna One',serif;
font-weight:700;
font-size:18px;
color:#fff;
width:50%;
margin-left:105px;
margin-top:30px
}
span{
color:green
}
#myForm div{
color:red;
font-size:14px
}
Conclusion:
We showed you form validation by using Ajax, PHP and javascript, Keep following us to learn more.
18 Replies to “Form Validation Using Ajax”
sir can i use validation without using php???
Yes of course, You can use either Javascript or jQuery for form validation but, remember, these scripting languages are used at client side and hence, it notifies error to user before form submission. This reduces unnecessary page reloads on server side. But, PHP is a server side scripting language therefore, it becomes mandatory to apply validation at server level in security aspects.
Thank you sir.
Very nice
hello admin can you tell me about the work of $value = $_GET[‘query’];
$formfield = $_GET[‘field’]; in validation.php page?
Hello Shazim,
$value = $_GET[‘query’]
$value is a variable that is the storing the field value. When onblur event is occurred a validate function is called : onblur=”validate(‘username’, this.value)” , in this “username” is a parameter in a string form and “this.value” is the field value.
so in the function validate(field, query) , field refers to username and query refers to field value.
and when ajax functioning takes place these values are stored in $value and $formfield in php page for further validation
Hope you have got that.
Thanks & Regards,
FormGet Team.
How can I use this form validation in JSP ?
I need more details and also the requirements(setup to be configured) in other to accomplish this excellent method of form
validation!!!!!!!!
Thank you
Dear,
i want insert data and store to database,how , where its used insert query above the code ,please some one help me,i am new to learn php
Go to w3schools.com and study php.
“INSERT INTO table name set fieldname=value”;
Very nice tutorial showing a real world application of ajax validation. Code is clear and concise making it easy to understand.
when i submit the value in database through of post…its not showing any value in my database..and its not submiting the value…but when i use input type=”submit” than it submitted the value but validation not work properly …..pls tell me what is an answer……
HI
i download ajax contact form validation code.and it’s run but it’s showing errors how to fix the error
ERROR:
Valid”; } } // Check Valid or Invalid password when user enters password in password input field. if ($formfield == “password”) { if (strlen($value)
Hello sir.,
this is a nice tutorial. and its working fine for me but there is one problem. when i submit the form then it show a popup (alert) box with error msg. but after that it will not show that form it will go for submit option. i couldn’t find out the solution. please help me to get out this problem.
thank you
thank you for the wonderful example. it really helps us to learn the programming language
keep up the good work.
how can i submit the form once validation is complete??
1. If i am not wrong , we can validate any form using Ajax. To use Ajax we need jquery library. in the jquery library, developers use some scripts. For example, jquery.min.js. This script is built using javascript (.js). But, my doubt is, if the user disables the JavaScript on the browser, that means jquery.min.js is not worked too.. Because, the jquery.min.js is built using JavaScript as we can see the extension (.js).
2. question is can we validate form using only php ? Why we need both server side and client side validations ? Is the server side validation is sufficient ? Why we need extra effort ?
3. Can we do all the validation using only php (exact like JavaScript including character validation, email validation ) ?
Great, thanks for the real-life example of Ajax data validation. I am looking for ClickFunnels Input data validation request processing help. Any idea, how can I solve that?