This example shows how you can include a ‘check availability’ option in a registration form using Ajax, PHP and MySQL. Using HTML input
element, user enters the email id and submits to the server side PHP script ‘isavailable.php’
using Ajax. ‘isavailable.php’ script
checks whether the email id is already available in the database table or not
and returns the status as responseText.
checkavailability.php
This PHP file contains the form and the Ajax script to submit the email id to the server side PHP script (isavailable.php) and display the response on the page.
<!DOCTYPE html>
<html>
<head>
<title>Check Availability - Ajax, PHP and MySQL </title>
<script>
function
checkavailability(){
var xmlhttp;
if
(window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code
for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if
(xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("divInfo").innerHTML=xmlhttp.responseText;
}
}
url =
"isavailable.php";
param = document.getElementById('txtemail').value;
url = url +
"?txtemail=" + param;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<table
align="center">
<tr>
<td
colspan="2"><h2>Check Availability</h2></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" size="40"
id="txtemail" name="txtemail"></td>
</tr>
<tr>
<td></td>
<td><input type="button" id="cmdcheck"
name="cmdcheck" value="Check Availability"
onclick="checkavailability()"></td>
</tr>
<tr>
<td
colspan="2"><div
id="divInfo"></div></td>
</tr>
</table>
</form>
</body>
</html>
isavailable.php
This PHP file extracts the email id submitted to the server from $_REQUEST array and check whether this id is available in the table by using PHP mysql functions. The availability status is sends back to the requested page.
<?php
$email =
$_REQUEST['txtemail'];
$dblink=mysql_connect("localhost","root","");
mysql_select_db("dbcheckavailability", $dblink);
$sql="SELECT
* FROM tblmember WHERE email='" . $email . "';";
$result=mysql_query($sql, $dblink);
$responseText
="";
if
(mysql_num_rows($result)) {
$responseText
= "Sorry, <b>" . $email . "</b> is already in
use!";
}
else {
$responseText
= "Congratulation, <b>" .
$email . "</b> is available!";
}
echo
$responseText;
mysql_close($dblink);
?>
Table
Structure
Thsis is the structure of the table that has to be created in MySQL for this example.
--
-- Database: `dbcheckavailability`
--
--
--------------------------------------------------------
--
-- Table structure for table `tblmember`
--
CREATE TABLE IF NOT EXISTS `tblmember` (
`firstname` varchar(30) NOT NULL,
`lastname` varchar(30) NOT NULL,
`email` varchar(40) NOT NULL,
UNIQUE KEY `email` (`email`)
);
INSERT INTO `tblmember` (`firstname`,
`lastname`, `email`) VALUES
('anand', 'kumar', 'csnotes32@gmail.com');
Output