Check Username Availability using Ajax in JSP - Onlyxcodes - onlyxcodes

Friday, 4 January 2019

Check Username Availability using Ajax in JSP - Onlyxcodes

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

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

That sounds confusing but it doesn't actually. Very few lines of code the Ajax method will help achieve this feature. This is a very popular feature added by Facebook social media and Gmail's email service provider that site is assigning unique usernames for each user to enable access to the login.

Let's start the tutorial we've got this amazing feature to achieve.

Check Username Availability Using Ajax in JSP - Onlyxcodes

Table Content

1. Database and Table

2. Text Box Codes

3. 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

Note – I initially built an index.jsp page, and stored text box and jquery / ajax codes within this page.

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. jQuery / Ajax Codes

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 single small JSP file that involves JSP script and works peacefully at backend and called through the function $.ajax( ).

This file scans the username from the database if the username is detected then sends the username available to ajax, otherwise it sends sorry username already exists. 

<%@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();
        }
    }
%>


Thank you for the reading article using these codes to check duplicate user id, email address from the database and more depending on your custom requirement.

Download Codes

No comments:

Post a Comment