kunal
kunal

Reputation: 163

Handle Ajax sucess and error in jsp

I have Form in JSP which have two input boxes along with submit and clear button like this

<form name="loginForm" method="GET" action="Ajaxexample" id="loginForm">
 <table>
 <tr>
 <td>From Date</td><td><input type="text" name="n1" value=""/></td>
 </tr>
 <tr>
 <td>End Date</td><td><input type="text" name="n2" value=""/></td>
 </tr>
 <tr></tr>
 <tr>
 <td><input type="submit" name="validpro_insert" value="Insert"></td>
 <td><input type="reset" name="validpro_clear" value="Clear"></td>
 </tr>                     
 </table>
 </form>

As I have called the servlet using get method in form tag which is used to get data from database via JDBC API and to handle the response I have use ajax like this

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    

         processRequest(request, response);
         System.out.println("In get");
          PrintWriter out = response.getWriter();
          String responseStr = "";
          responseStr = addUser(request); // Return either error/success
          System.out.println("Reponse:" + responseStr);  
           response.setContentType("application/json"); 
           response.setCharacterEncoding("utf-8"); 
           response.getWriter().write(responseStr);
           out.print(responseStr);

As I have to write some code to get data from DB in servlet and return that response to ajax which handle success and error on the same jsp like this

<script type="text/javascript" src="js/jq.js"></script>   
   <script type="text/javascript">

        var form = $('#loginForm');
        form.submit(function () {
        $.ajax({
        type: form.attr('method'),
        url: form.attr('action'),
        data: form.serialize(),

          error: function (theRequest,textStatus, errorThrown) {
                     // Success = false;
                      alert (theRequest.responseText);
                      alert(errorThrown);
                   alert('No graph found');//doesnt goes here
            },
        success: function (data) {

                var result=data;
                alert(result);
        }     
                });
                return false;
            });
        </script>

But the problem is that I am not getting any value from servlet in ajax to handle success or error

I think I am facing this problem due to servlet doget() method code.. if there is any other problem plz let me know. Any help should be appreciated

Upvotes: 1

Views: 3439

Answers (2)

kunal
kunal

Reputation: 163

with these changes in my code, it runs successfully

 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            try (PrintWriter out = response.getWriter()) 

                 String responseSend = "";

            String from = request.getParameter("n1");
            String to = request.getParameter("n2");    

              if ((from == null) || (from.equals(""))) {

                System.out.println("From null");
                responseSend = "error";

            } 
              else if ((to == null) || (to.equals(""))) {

                System.out.println("End null");
               responseSend  = "error";

            }
              else{            
                      //jdbc code              
            System.out.println("got it");
            int n1 = Integer.parseInt(request.getParameter("n1"));
            int n2 = Integer.parseInt(request.getParameter("n2"));
            responseSend = "code";           
              }

             out.print(responseSend);

        }          
            }

        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
           System.out.println("In get");
            processRequest(request, response);
    }

As I have added a new method processrequest() with request and response parameters which will return the text/HTML to our Ajax code on the same jsp.Firstly I am confused with success/error in ajax code but now I have found that

 error: function (theRequest,textStatus, errorThrown) {
                          alert (theRequest.responseText);
                          alert(errorThrown);
                },

  success: function (data) {

                var result=data;
                alert(result);
        }   

The error will be called when it doesn't found servlet at given URL and success will be called when it successfully call the servlet with given type and servlet URL.

Upvotes: 1

Rohit Chauhan
Rohit Chauhan

Reputation: 1159

I have pasted my code here that work well

Try changing your parameter

Your JSP Page

<script src="http://code.jquery.com/jquery-1.10.2.js"
type="text/javascript"></script>

<form id="form">
    Enter Your Name: <input type="text" id="userName" />
</form>
<br>
<br>

<strong>Ajax Response</strong>:
<div id="ajaxGetUserServletResponse"></div>

here is your ajax

$(document).ready(function() {
$('#form').submit(function() {
    $.ajax({
        url : 'GetUserServlet',
        data : {
            userName : $('#userName').val()
        },
        success : function(responseText) {
            $('#ajaxGetUserServletResponse').text(responseText);
        }
    });
});

});

your servlet file

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String userName = request.getParameter("userName").trim();
    if(userName == null || "".equals(userName)){
        userName = "Guest";
    }

    String greetings = "Hello " + userName;

    response.setContentType("text/plain");
    response.getWriter().write(greetings);
}

}

Upvotes: 0

Related Questions