Check email availability using jQuery’s ajax (Part 1. hard way)
Here we will make a form such as registration form, which is contain of email field, that need to be checked for its availability.
Naturally, we will check its (email) availability by let the form submitted once, then processed it in the server. However by using AJAX, we can make it possible to check its availability on client-side. Again, jQuery will make it much easier to accomplish.
Before we start, we need jQuery library to complete this tutorial.
This part, we will try to make it using common jQuery’s ajax function, that need several setting to accomplish.
Then, lets begin..
Here is the registration-page, named register.html.
register.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="jquery.js"></script>
<title>Email Checker</title>
<script type="text/javascript">
$(document).ready(function(){
$('input#process').click(function(){
var requested_email = $('input#email').val();
$.get("email_checker.php", {email: requested_email},
function(data){
if(data){
$('form#my_form').submit();
}
else{
$('span#error_msg').text('Email '+requested_email+' have been used');
return false;
}
},
"json" // here you specify that the return type is JSON
);
});
});
</script>
</head>
<body>
<form name="my_form" id="my_form" method="post" action="process.php">
<h1>Check email availability</h1>
<input type="text" name="email" id="email" /><span id="error_msg"></span>
<input type="button" value="Process" id="process" />
</form>
</body>
</html>
Then, we will make the ajax page, which will process our register.html‘s ajax request. Lets called it email_checker.php. This page will only output two type of response, true or false depend on the availibility of email given. If the email is available (allow to register) then the output is true, otherwise it is false, than mean the user need to provide another email to continue registration process.
Here it is:
email_checker.php
<?php
$registered_email = array( 'john@doe.com', 'jonhy@doe.com' );
$requested_email = $_GET['email'];
if( in_array($requested_email, $registered_email) ){
echo 'false';
}
else{
echo 'true';
}
?>
The last, we need process.php that will finish the process.
process.php
<?php
$requested_email = $_POST['email'];
echo "<h1>$requested_email</h1> is available !";
?>
Also, you can download the complete version of this tutorial to compare.
[...] a comment » On our previous tutorial (Part 1), we have deal with hard way of checking email availability using jQuery ajax. Now we will [...]
Check email availability using jQuery’s ajax (Part 2. easy way) « Bear and Share [my] Knowledge
2009/06/29 at 08:50