Vicky Nandne Vicky Nandne - 4 months ago 8
Javascript Question

Ajax using JQuery success function is not called

1. servlet file

public class StudentController extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("inside servlet");

dao dao=new daoimpl();
String action=(request.getParameter("action"));
if(action.equalsIgnoreCase("login")){
System.out.println("inside login");
Student student=new Student();
System.out.println(request.getParameter("username"));


student.setUsername(request.getParameter("username"));
student.setPassword(request.getParameter("password"));
ArrayList<Student>al=dao.getAllStudent(student);
Gson gson=new Gson();
//PrintWriter pw=response.getWriter();
String json = gson.toJson(al);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}




index.jsp
<html>
<head>
<script src="js/jquery.min.js" type="text/javascript" ></script>
<script type="text/javascript">
$(document).ready(function() {
$('#login').click(function(event) {
var uname = $('#username').val();
var pass = $('#pass').val();
alert(uname+"-----"+pass);

alert("on click");
$.post("Controller?action=login",{
username : uname,
password : pass
},function(data) {
alert("sucess");
var json=$.parseJSON(data);
alert(json);
});
});
});
</script>

</head>
<body>
<form action="login" method="post">
User Name:<input type="text" name="uname" id="username"><br>
Password:<input type="text" name="password" id="pass"><br>
<input type="submit" value="Login" id="login">
<a href="registration.jsp">Register</a>
<h3 align="center">student Details</h3>
<div id="tablediv">
<table cellspacing="0" id="studenttable">
</table>
</div></form></body>
</html>





not even sucess alert working in the code,please suggest me i m new for jquery thanks in advance..

Answer

Try this

<script type="text/javascript">
$(document).ready(
  function() {
      $('form').submit(function(event) {
        event.preventDefault();

         var uname = $('#username').val();
            var pass = $('#pass').val();
            alert(uname+"-----"+pass);            
            alert("on submit");


            $.ajax(
              {
                url:"Controller?action=login",
                data: {username : uname,password : pass}
                type:'post',
                cache:false,
                timeout:8000
              }
            ).done(function(data){
                alert("sucess");    
                var json=$.parseJSON(data);
                alert(json);

            }).fail(function(jqxhr, textStatus, error){
              alert(textStatus);
              alert(error);
            });
      });
    }
  );
</script>
Comments