Monday, 1 September 2014

Sample code for implementing "check availability option in registration form" using Ajax, PHP and MySQL

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.


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>
        <title>Check Availability - Ajax, PHP and MySQL </title>
        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) {




        url = "isavailable.php";

        param = document.getElementById('txtemail').value;                       

        url = url + "?txtemail=" + param;






    <table align="center">
            <td colspan="2"><h2>Check Availability</h2></td>
        <td><input type="text" size="40" id="txtemail" name="txtemail"></td>
        <td><input type="button" id="cmdcheck" name="cmdcheck" value="Check Availability" onclick="checkavailability()"></td>
            <td colspan="2"><div id="divInfo"></div></td>       



 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.

    $email = $_REQUEST['txtemail'];

    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;

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`

  `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', '');


No comments:

Post a Comment