Wednesday, 29 January 2014

Java Jquery Ajax Sample

/**
Prerequest Sets
       Please download  jquery.js and add it in  your js folder
*/
HTML Page:
<html>
<script type="text/javascript" src="js/jquery.js"></script>
<script>
function callAjax(){

$.ajax({
            var userName=$( "#uname" ).val();
            var formData = {uname:userName};
            url : 'LoginIDActivityHandler',
            type: "POST",
            data : formData,
            success: function(responseText)
            {
                     
                      if(responseText=='y'){
                             alert('valid user');
                           document.login.submit();
                      }else {
                          alert('invalid user');
                            return false;
                      }
            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                alert(errorThrown);
                return;
            }
        });
}
</script>

<form name="jqueryajax">
<input type="text" class="form-control"  id="uname" name="uname"/ >
<input type='button' onClick='callAjax();'>
</form>
</html>
web.xml

<servlet>
    <description></description>
    <display-name>LoginIDActivityHandler</display-name>
    <servlet-name>LoginIDActivityHandler</servlet-name>
    <servlet-class>LoginIDActivityHandler</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginIDActivityHandler</servlet-name>
    <url-pattern>/LoginIDActivityHandler</url-pattern>
  </servlet-mapping>

Servlet File

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created By B.Balamurugan
 */
public class LoginIDActivityHandler extends HttpServlet {
 private static final long serialVersionUID = 1L;

 @Override
 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  String userid = request.getParameter("uname");
  if (userid.equals("bala")) {
   response.getWriter().write("y");
   return;// to avoid illegal statement exception

  } else {
   response.getWriter().write("n");
   return;// to avoid illegal statement exception
  }
 }

}


No comments:

Post a Comment