Dynamic form validation using JAVASCRIPT and AJAX
Hello...Web Application Developers(Beginners)
Today you will learn how to dynamically validate a form using AJAX and JAVASCRIPT.
If you already know how to do it then your are at wrong place DUDE.
So without wasting time lets start ....zzZZZz
#*The above example will take the username from username and dynamically checks whether this username is already taken by other user or not*#
Lets understand the logic behind validating form dynamically.
The block diagram clearly shows the flow of data through our system.
Files required.
1)form.html(To allow user to input data)
2)validate.js(Main validation function to send an AJAX request to find if user already exists in the system)
3)ajax.js(An AJAX module to create an AJAX request)
4)php file (to serach in database if username is already in use or not?}
1)form.html
code:
Username<input id="uname" type="text" onblur = "val(id)" /><span id = "valspan"></span>
Output
Username
*here we will be dealing with only username but you can apply the same logic to all your validation
2)validate.js
<script src="ajax.js"></script>
<script type= "text/javascript">
function val(txtid){
var username = document.getElementById(txtid).value;
var spanstatus = document.getElementById("valspan").value;
if(username.length == ' '){
spanstatus.innerhtml = "Please enter an username";
}
else{
var ajax = ajaxobj("POST","checkname.php");
ajax.onreadystatechange = function(){
if(ajaxreturn(ajax)==true){
var response = ajax.responseText;
if(response == "ok"){
spanstatus.innerhtml = "OK";
}
else{
spanstatus.innerhtml = "Sorry,but this username is already taken";
}
}
}
ajax.send("user="+username);
}
}
</script>
3)ajax.js
function ajaxobj(method,url){
var x = new XMLHttpRequest();
x.open(method, url,true);
x.setRequestHeader("Content-type","application/x-www-form-urlencoded");
return x;
}
function ajaxreturn(x){
if(x.readyState==4 && x.status==200){
return true;
}
}
4)php file
<?php
include_once("db_connect");
if(isset($_POST['user'])){
include_once("db_connect");
$user = $_POST['user'];
$sql = "select id from table where username='$user';
$query = mysqli_query($db_conx,$query);
$numrow = mysqli_num_rows($query);
if($numrow < 1){
echo "ok" //This is what goes back to ajax in val.js if username doesn't exists in the DB//
exit();
}
else{
echo "Username in use";
//This is what goes back to ajax in val.js if username exists in the DB//
exit();
}
}
exit();
?>
No comments:
Post a Comment