Share this blog!

How to check uniqueness of a username using JavaScript (AJAX on JSP backend)

You may have already come across situations where web forms statically alert you about the availability of a username or email without loading another page or refreshing the page. In this post, we will be discussing how to achieve this using AJAX script and JSP.



Let's assume our html form is as follows. Please note that I'm adding only the relevant components. 

<form name="myForm" onsubmit="return validate()">
    <label>Username:</label>
    <input type="text" name="userName" onblur="checkUniqueness()" />
    <span id="eMsg" style="color:red;"></span>
</form>

In this example, I'm using onblur which is triggered when the focus is lost, for example when the user selects the next input or clicks somewhere else on the form after typing the username.There are many other options you can use such as a separate button to check it or check during validation.  I am also using a span with red color text to display the error message.

The onsubmit="return validate()" is also important. If the validate is returning true, or there is no validate, the form will be submitted while we are checking the username and the process after submission will be occurring. The validate method prevents a form from submitting under given conditions. Therefore it is important that there is a condition that prevents the form from submitting during our username checking AJAX call.

The JavaScript function with the AJAX call is as follows:

function checkUniqueness() {
          var xmlhttp = new XMLHttpRequest();
          var username = document.forms["myForm"]["userName"].value;
          var url = "exist.jsp?username=" + username;
          xmlhttp.onreadystatechange = function () {
               if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
                      if (xmlhttp.responseText.includes("NO")) {
                            document.getElementById("eMsg").innerHTML = "Username already exists";
                      }
               }
          };
          try {
                xmlhttp.open("GET", url, true);
                xmlhttp.send();
          } catch (e) {
                alert("unable to connect to server");
          }
}

As you can see, we need a JSP that has the ability to check the uniqueness by reading data from somewhere, probably a database. The following represents a comprehensive example of the JSP, including the database call.

<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="DB.DBConnectionHandler"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.Connection"%>
<%@page import="Controller.DBDataList"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
    if (null != request.getParameter("username")) {   //check if parameter is there
        String uname = request.getParameter("username");  //extract username parameter
        try {

            //create connection and make the db call
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/highertradesmendb", "root", "hahaha");
            String query = "SELECT * FROM user where username=?";
            PreparedStatement ps = con.prepareStatement(query);
            ps.setString(1, uname);
            ResultSet rsetUser = ps.executeQuery();

            //check existance
            boolean stat = !rsetUser.first();
            con.close();

            //print the result
            if (stat) {
                out.print("YES");
            } else {
                out.print("NO");
            }

        } catch (Exception e) {
            System.out.println("get unique username error -  " + e);
        }
    }
%>

What is retrieved in the JavaScript is what we print to out.print and a string comparison is done in the JavaScript to define the results.



Next PostNewer Post Previous PostOlder Post Home

0 comments:

Post a Comment