kartik
kartik

Reputation: 100

Connect database using Ajax?

I want to use Ajax for UserId validation, Can anyone help me out in connecting database?

Here is my JSP page . enter code here

   <script type="text/javascript">

    /* 
   * creates a new XMLHttpRequest object which is the backbone of AJAX, 
  * or returns false if the browser doesn't support it 
  */
   function getXMLHttpRequest() { 
   var xmlHttpReq = false; 
   // to create XMLHttpRequest object in non-Microsoft browsers 
    if (window.XMLHttpRequest) { 
      xmlHttpReq = new XMLHttpRequest(); 
     } else if (window.ActiveXObject) { 
     try { 
      // to create XMLHttpRequest object in later versions 
      // of Internet Explorer 
      xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP"); 
     } catch (exp1) { 
       try { 
        // to create XMLHttpRequest object in older versions 
        // of Internet Explorer 
        xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); 
       } catch (exp2) { 
         xmlHttpReq = false; 
       } 
    } 
   } 
   return xmlHttpReq; 
   } 
  /* 
  * AJAX call starts with this function 
   */
  function makeRequest() 
  { 

 var c=document.getElementById("userid").value;
     var xmlHttpRequest = getXMLHttpRequest(); 
    xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest); 
   xmlHttpRequest.open("POST", "../userid", true); 
   xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-   urlencoded");   
   xmlHttpRequest.send("requestType=ajax&userid="+c); 
    } 

   /* 
   * Returns a function that waits for the state change in XMLHttpRequest 
   */
 function getReadyStateHandler(xmlHttpRequest) { 

   // an anonymous function returned 
   // it listens to the XMLHttpRequest instance 
   return function() { 
    if (xmlHttpRequest.readyState == 4) { 
     if (xmlHttpRequest.status == 200) { 
     document.getElementById("print").innerHTML = xmlHttpRequest.responseText; 
     } else { 
     alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText); 
     } 
    } 
  }; 
 }


    <form  action="<%=application.getContextPath() %>/Login"  method="post"      name="myForm">

  <table>
   <tr>
  <td>UserId</td>
  <td><input type="text" name="userid" id="userid" onblur="makeRequest()" > </td>
   </tr>

   <tr>
   <td>Password</td>
   <td><input type="password" name="password" > </td>
   </tr>

   <tr><td></td>
    <td><input type="submit" name="submit" value="Submit"></td>
   <td><input type="hidden" name="requestType" value="Login"> </td>
  </tr>

  </table>
 </form>
   </script>

Please help me out for this. I require user id validation. If correct userid then it should display name, else display error msg.

Upvotes: 0

Views: 1740

Answers (2)

Abhishek Nayak
Abhishek Nayak

Reputation: 3748

To validate user:

  • Create a service/dao class with a method that interacts with database and returns boolean type.
  • create a Servlet and implement doPost() and use created service/dao class.
  • Finally, return true if user found, otherwise false in response.
  • In javascript display the message or error based on response from server.

for example:

create UserService class that will be look like:

public class UserService {

        public Connection getConnection() throws SQLException {
            try {
                Class.forName("com.mysql.jdbc.Driver");//register database driver
            } catch (ClassNotFoundException e) {        
                e.printStackTrace();
            }
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "****", "*****");        
        }

        /**
         * Checks a User id is exists in database using given user id<br/>
         * <b>Note:</b> this method closes Connection and PreparedStatement you have passed as parameter
         * @param pStatement A PreparedStatement instance with query to fetch result
         * @return a true if user id found in database, else false returned.         
         */
        public boolean isUserExists(final String userId) {      
            if(userId==null || userId.isEmpty())
                return false;

            //declare required fields
            Connection connection = null;
            ResultSet rSet = null;
            PreparedStatement pstmt = null;
            boolean isExists = false; //set userId exists false initially

            try{
                connection = getConnection(); //get a connection to intract with database.
                //create a PrepareStatement instance to fetch user id from database
                pstmt = connection.prepareStatement("SELECT login FROM users WHERE login=?"); 
                pstmt.setString(1, userId); // set user id which you want to retrieve from DB.
                rSet = pstmt.executeQuery(); //execute the query

                if(rSet.next()){ //check if you got any
                    System.out.printf("User id %s found",rSet.getString(1));
                    isExists = true; //user id exists, set true
                }                   
            }catch(SQLException e){
                e.printStackTrace();
            }finally{
                //close all like: Connection, ResultSet and PreparedStatement etc
                try { if (rSet != null) rSet.close(); } catch (Exception e) {};
                try { if (pstmt != null) pstmt.close(); } catch (Exception e) {};
                try { if (connection != null) connection.close(); } catch (Exception e) {};
            }

            return isExists;
        }
}

and the Servlet will look like:

@WebServlet("/validateUserIdByAjax")
public class ValidateUserIdByAjax extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private UserService userService = new UserService();        

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doPost() invoked..");
        // Set response content type
        response.setContentType("text/html");       
        // Set encoding
        response.setCharacterEncoding("UTF-8");

        //get user entered id
        String userId = request.getParameter("userid");
        //return userid status 
        response.getWriter().print(userService.isUserExists(userId));                   
    }

}

Then, check response from server and show message in javascript like:

 function getReadyStateHandler(xmlHttpRequest) { 

   // an anonymous function returned 
   // it listens to the XMLHttpRequest instance 
   return function() { 
    if (xmlHttpRequest.readyState == 4) { 
     if (xmlHttpRequest.status == 200) { 
         var $print = document.getElementById("print");
         var res = xmlHttpRequest.responseText;
         console.log('user status: '+res);
         if(res=="true"){
             $print.innerHTML = '<span style="color:red;">user id exists!</span>';
         }else{
             $print.innerHTML = '<span style="color:green;">user id available!</span>';
          } 
     } else { 
     alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText); 
     } 
    } 
  }; 
 }

that's it.


Note:

  • your AJAX POST url should match your Servlet url-patteren, in my case validateUserIdByAjax is the servlet url-pattern so AJAX url will look like:

    xmlHttpRequest.open("POST", "validateUserIdByAjax", true);.

  • and Database driver class should be available in CLASSPATH, in my case i have used mySql so mysql-connector-java.jar is added to CLASSPATH.

In your question not have any element by id print, So please add to see the message while using above example, like: <span id="print"></span>

Upvotes: 1

Kuldeep Choudhary
Kuldeep Choudhary

Reputation: 775

make a jsp page with database connectivity that will be requested for output.....

in your ajax request send user_id and in jsp page get userid and check it from database ...if available then send true to ajax otherwise false.....

or in ajax response get message result from jsp page...make condition to handle this........

Upvotes: 0

Related Questions