Pages

Thursday 6 March 2014

Check username availability using ajax and jsp

We will see how to check the user name availability in the database with ajax,  this is some thing what we can find out at time of gmail signup.

Files Required:
  • register.jsp
  • unameverify.jsp
-------------------- ----------
register.jsp

<%@ page language="java" pageEncoding="ISO-8859-1"%>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="tcal.css" />
        <script type="text/javascript" src="tcal.js"></script>
        <script src="js/main.js" type="text/javascript"></script>
        <script type="text/javascript" src="jquery-1.10.2.min.js"></script>

        <script type="text/javascript">
                 var unameflag = false;
                 var pwordflag = false;
                 var pword2flag = false;
                  var unamevalidated = false;
                 var emailvalidated = false;
                  var xmlhttp = false;
                  try
                 {
                     //If the javascript version is greater than 5.
                     xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                }
                 catch (e)
                 {
        //If not, then use the older active x object.
         try
         {
            //If we are using IE.
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         }
         catch (E)
         {
            //Else we must be using a non-IE browser.
            xmlhttp = false;
         }
    }
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
    {
        xmlhttp = new XMLHttpRequest();
    }
    function grabword (theelement)
{
//If there is nothing in the box, run Ajax to populate it.
    switch (theelement)
    {    case "uname":
                //do javascript validation
                validate(theelement);
                //do ajax functionality
                if(unamevalidated)
                {
                    var unametemp = document.getElementById(theelement).value;
                    if ( unametemp != "")
                    {    serverPage = "unameverify.jsp?uname="+unametemp;
                        var obj = document.getElementById("unamemsg");
                        xmlhttp.open("GET", serverPage, true);
                        xmlhttp.onreadystatechange = function()
                        {
                        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
                            {
                                                                var indexu=xmlhttp.responseText.indexOf("available");
                                                                if(indexu != -1)
                                {
                                    obj.innerHTML = "<font color='green'> <img src='images//tick.gif' /><b>Valid</b> </font>";
                                    unameflag = true;
                                }
                                else
                                    obj.innerHTML = " <font color='red'><img src='images//cross4.png' />User Name already exists</font>";
                                        }
                        }
                        xmlhttp.send(null);
                    }
                    else
                    {
                        document.getElementById(theelement).innerHTML = "";
                    }
                }
                break;
        default:
        validate(theelement);
    }
}   
function validate(theelement)
{
var uname;
 switch (theelement)
    {
 case "uname":
            var unamecheck=new RegExp("^[a-zA-Z0-9]+$","g");
            uname=document.getElementById("uname").value;
            var uflag = 0;
            if(uname != "")
            {
                if(!uname.match(unamecheck))
                {
                    document.getElementById("unamemsg").innerHTML = "<font color='red'> Spaces and special charecters are not allowed</font>";
                    uflag = 1;
                     obj.innerHTML = "<font color='green'> </font>";
                   
                }
                if(uname==""||uname.length < 4||uname.length > 10)
                {
                    document.getElementById("unamemsg").innerHTML = "<font color='red'> min 4 characters and max 10 characters</font>";
                    obj.innerHTML = "<font color='green'> </font>";
                    uflag = 1;
                    //obj.innerHTML = "<font color='green'> </font>";
                }
                if(uflag == 0)
                unamevalidated = true;
            }
            break;
     }
}
function checkfun(){
    if(unameflag==false){
    // alert("exited ");
     document.getElementById("uname").focus();
     return false;
    }
    if(unamevalidated==false){
    // alert("exited ");
     document.getElementById("uname").focus();
     return false;
    }   
    else
    return true;
    }
    function setFocus(){
    document.getElementById("uname").focus();
    return false;
    }
    </script>
    </head>
    <body onload="return setFocus()">
        <div id="divpage"
            style="position: absolute; overflow: hidden; left: 350px; top: 10px; width: 300px; height: 80px; z-index: 0">
            <h2>
                <font color="#036A71">Registration Form</font>
            </h2>
        </div>
        <html:form action="/registrationform" onsubmit="return checkfun()">
            <div id="divpage"
                style="position: absolute; overflow: hidden; left: 0px; top: 70px; width: 300px; height: 360px; z-index: 0">
                <table>
                        <tr>
                        <td>
                            UserName:
                            <font color="red">*</font>
                        </td>
                        <td>
                        <input id="uname" type="text" name="uname" required
                                pattern="[a-zA-Z0-9]+" maxlength="10"
                                x-moz-errormessage="Spaces and special charecters are not allowed"
                      onfocus="if(this.value == '') document.getElementById('unamemsg').innerHTML = '';"
                                onblur="grabword(this.id)" size="20">
                            <span id="unamemsg" style="height: 20px;"> </span>
                        </td>
                    </tr>
                </table>
            </div>
        </html:form>
    </body>
</html>
------------------------
unameverify.jsp

<%@page import="java.sql.*" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page language="java" %>

<%
String uname= request.getParameter ("uname");
 try {
          Class.forName("com.mysql.jdbc.Driver");
           Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/acnmain","jbossapp","JBossAppDE");
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery("select * from registrations where re_username='"+uname+"' ");
           
if(!rs.next ())
{
// for plain text response:
// Or for XML formatted response:
        response.getWriter ().print ("available");
//System.out.println("after sending response");
}
else
{
//nothing to show
        System.out.println ("Unavailable");
        response.getWriter ().print ("User Name already exists");
}

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error in Login");
        }

%>

 ------------------------------------

Note: You must have mysql-connector.jar in the lib folder of you applications. And  place two required images related to the text (valid and already existed) with name tick.gif  and cross4.png.

Ex:
Username: User Name already exists

3 comments:

  1. thank u for the post...
    Its very helpful but i am not getting the message when focus again come to the register.jsp
    or any entry in web.xml is required

    ReplyDelete
  2. Hi Akshay,

    Nothing is required in web.xml. To connecting the database mysql-connector jar file and table named registrations is mandatory.
    and the url you need to use in the browser is
    http://localhost:8080/projectname/register.jsp

    ReplyDelete
  3. will it insert even after showing already exists message??

    ReplyDelete