0

I am new to jquery and ajax. I want to check whether the given username is present in my DB or not if it is available I want to give an alert by passing a message called username already exist. I am trying to apply the blur method of jquery so before submitting the form I can get the status about that username. Please help me to solve this.

This is my JSP page

<body>

    <div class="container registration">
        <fieldset class="border p-2">
            <legend class="w-auto">Registration Form</legend>
            <form action="registration" method="post" id="registrationForm"
                onsubmit="return validation();">
                <div class="row" style="padding-bottom: 20px">
                    <div class="col">
                        <input type="text" class="form-control" name="firstName"
                            placeholder="First name" id="fname"> <span id="firstname"
                            class="text-danger font-weight-bold"></span>
                    </div>
                    <div class="col">
                        <input type="text" class="form-control" name="lastName"
                            placeholder="Last name" id="lname"> <span id="lastname"
                            class="text-danger font-weight-bold"></span>
                    </div>
                </div>

                <div class="row" style="padding-bottom: 20px">
                    <div class="col">
                        <input type="text" class="form-control" name="userName"
                            placeholder="UserName" id="uname"> <span id="username"
                            class="text-danger font-weight-thin"></span>
                    </div>
                    <div id="ajaxGetUserServletResponse"></div>
                </div>
                <!-- below jquery things triggered on onblur event and checks the username availability in the database -->
                <script type="text/javascript">
                    $(document).ready(function() {
                        alert("js is working");
                        $('#uname').blur(function() {
                            alert("blur is working")
                            $.ajax({
                                    type : 'post',
                                    url : 'registration',
                                    data : {
                                                uname : $('#uname').val()
                                            },
                                            success : function(responseText) {
                                                $('#ajaxGetUserServletResponse').text(responseText);
                                            }
                                    });
                            });
                    }); 
                </script>

This is my servlet

@WebServlet("/registration")
public class RegistrationServlet extends HttpServlet {
    Registration userDetails = Utility.getRegistration();
    // RegistrationService registrationService = Utility.getRegistrationService();
    UserDetailsService userDetailsService = Utility.getUserService();
    JSONArray array = null;
    JSONObject jsonObject;
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String fName = req.getParameter("firstName");
        String lName = req.getParameter("lastName");
        String uName = req.getParameter("userName");
        String email = req.getParameter("email");
        String contactNumber = req.getParameter("contactNumber");
        String password = req.getParameter("password");

        userDetails.setFirstName(fName);
        userDetails.setLastName(lName);
        userDetails.setUserName(uName);
        userDetails.setEmail(email);
        userDetails.setMobile(contactNumber);
        userDetails.setPassword(password);

        try {
            jsonObject = UserDetailsRepository.getOneUserDetails(uName);
            if (jsonObject != null) {
                String msg = "User is already exist";
                resp.setContentType("text/plain");
                resp.getWriter().write(msg);
            //  throw new UserAlreadyExistException("User is already exist");
            } else {
                boolean result = userDetailsService.addUser(userDetails);
                if (result) {
                    req.setAttribute("insert", "Data is added into the table successfully!!!");
                    resp.sendRedirect("index.jsp");
                } else {
                    req.setAttribute("message", "Something went wrong!!!");
                    resp.sendRedirect("error.jsp");
                }
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

rhenesys
  • 174
  • 1
  • 11
Amit
  • 1
  • 3
  • Solve what, exactly? You kinda neglected to give us an actual problem description … Please go read [ask], and then edit your question accordingly. – 04FS Dec 06 '19 at 08:59

1 Answers1

0

I understood you want to check if the user already exists. You are doing almost right.

 $.ajax({
                                type : 'post',
                                url : 'registration',
                                data : {
                                            uname : $('#uname').val()
                                        },
                                        success : function(responseText) {
                                            $('#ajaxGetUserServletResponse').text(responseText);
                                        }
                                });
                        });

You are sending data with a parameter named uname in your ajax but your servlet does not get nothing with that name. You should do something like:

String uName= req.getParameter("uname");

And work with uName to check what you want. I am not sure if that works like you want because your form is triggering the servlet too. You should differentiate the calls based on something like the name. When you call your ajax all other parameters will be null except uname you are sending (if the user typed something. Maybe check that first too?). But when sending the form the uname from ajax will be null.

Maybe something like this:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
    if(request.getParameter("userName") != null) {
        formCall(request,response);
    }

    if(request.getParameter("uname") != null) {
        ajaxCall(request,response);
    }
}

private void ajaxCall(HttpServletRequest request, HttpServletResponse response) {
    System.out.println("Ajax call " + request.getParameter("uname"));

}

private void formCall(HttpServletRequest request, HttpServletResponse response) {
    System.out.println("Form call " + request.getParameter("userName"));

}

The ajax call in the .blur jumps to the one method and the form submit to the other one.

Wrong behavior: if the user loads the page, clicks on the text field AND after that clicks the button, this will trigger the .blur and also the submit at the same time. Maybe you do not want that too.

rhenesys
  • 174
  • 1
  • 11