Check Username Availability using Ajax in JSP - onlyxcodes

Friday 4 January 2019

Check Username Availability using Ajax in JSP

In this tutorial, I’ll show you how to check username availability using Ajax in JSP.


If you want to enable users to log in to your website with a username and password, First, at the time of registration, you need to add a unique username to the database for every user. Once users register the desired username it is required to check the availability of live usernames from the database without the page being reloaded.


The live username check availability is a very popular feature most used in registration forms in web applications and using the Ajax method you can this feature.


check username availability using ajax in jsp - Onlyxcodes

Table Content

1. Database and Table

2. Text Box Codes

3. Check Username Availability by jQuery Ajax Codes

4. check.jsp


1. Database and Table

'username_available_db' is the database name I used here, establish the database and copy/paste the SQL code into your PhpMyAdmin to store user information. 


CREATE TABLE `tbl_user` (
  `id` int(11) NOT NULL,
  `username` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;

create user table with two fields id and username

Just insert one record in the table for checking, paste SQL code underneath to insert records. 


INSERT INTO `tbl_user` (`id`, `username`) VALUES
(2, 'Hamid');

insert one dumping record in user table

2. Text Box Codes

See the use of bootstrap packages to create simple text boxes. The users type their username in this text box after this text box indicates that the username exists or not.


<form role="form" method="post">                   
    <div class="form-group">
        <label>Enter Username</label>
        <input type="text" id="username" class="form-control" placeholder="enter username">
    </div>
    <span id="available"> <!--- data show this span tag --->
    </span>
</form>

3. Check Username Availability by jQuery Ajax Codes

In this code, If the user types username in the text box and clicks outside the box then blur() method event will occur.


As the name has been entered it will send ajax HTTP POST request to 'check.jsp' URL property file, this property is close to the form action attribute it carries the JSP filename for backend work.


And the 'data' property holds the info in the text box as text and is sent along with the request. The success function that gets the JSP script response and detects the user if the username exists or not.


The #username is textbox Id attribute and the and the .val() method getting entered value using that attribute.


<script type="text/javascript">
$(document).ready(function(){
   
    $("#username").blur(function(){
        
        var username =$("#username").val();
   
        if(username.length >= 3)
        {
            $.ajax({
                url:"check.jsp",
                type:"post",
                data:"uname="+username,
                dataType:"text",
                success:function(data)
                {
                    $("#available").html(data)
                } 
            });
        }
        else
        {
          $("#available").html(" ");
        }
        
   }); 
   
});    
</script>

5. check.jsp

This is a single small JSP code file that works silently at the backend side and is called through the function $.ajax( ).


This file scans the username from the database if a username is detected then it sends the username available message to Ajax, otherwise it sends Sorry username already exists message to Ajax.


<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%
    String dburl="jdbc:mysql://localhost:3306/username_available_db"; 
    String dbusername="root";    
    String dbpassword =""; 
    
    if(request.getParameter("uname")!=null) 
    {
        String user_name=request.getParameter("uname"); 
        
        try
        {
            Class.forName("com.mysql.jdbc.Driver"); 
            Connection con=DriverManager.getConnection(dburl,dbusername,dbpassword); 
           
            PreparedStatement pstmt=null; //create statement
            
            pstmt=con.prepareStatement("SELECT * FROM tbl_user WHERE username=? "); 
            pstmt.setString(1,user_name); 
            ResultSet rs=pstmt.executeQuery(); 
            
            if(rs.next())               
            {  
                %>
                <span class="text-danger">Sorry, <%=rs.getString("username")%> Already Exists ! </span>
                <%
            }
            else
            {
                %>
                <span class="text-success">Username is available</span>
                <%
            }

            con.close(); //close connection
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
%>

Download Codes

No comments:

Post a Comment

Post Bottom Ad