1

I am using $.ajax() function to call servlet in my application and i am forwarding request to anothor jsp page and setting request attribute.....I just want to know is it good approach to forward request and setting request parameter in ajax based servelt? Here is my sample code.....

          var id= $("#id").val();

          $("#add-btn").click(function(e) {                                                                                                 
                e.preventDefault();         
                var dataString ='action=insert'+'&id='+id
                console.log(dataString);
                $.ajax({
                    type: "POST",
                    url: "RecordHandler",
                    data: dataString,
                    success: function(data){  
                        console.log('Add');
                        $('body').html(data);
                        $('body').prepend('<div style="width:100%;text-align:center;"><h3 style="color:green" >Record Added Succesfully</h3></div>')
                    }
                });  

            });

and here is my servlet code......

  private static String UserRecord = "/list.jsp";

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

    String redirect = "";
    String action = request.getParameter("action");
    if (action.equalsIgnoreCase("insert")) {
      String id= request.getParameter("id");
      int uid = Integer.parseInt(id);
      RecordBean record = new RecordBean();
      record.setId(uid);
      dao.addRecord(record);
      redirect = UserRecord;
      request.setAttribute("records", dao.getAllRecords()); //Is it good approach to set request attribute in ajax based servlet?
      System.out.println("Record Added Successfully");

      RequestDispatcher view = request.getRequestDispatcher(redirect);//Is it good approach to redirect request in ajax based servlet?
      view.forward(request, response);
 }

How to do it using ajax without refreshing page...... even i use window.location.herf="list.jsp" in ajax success method it is refreshing page

Developer Desk
  • 2,294
  • 8
  • 36
  • 77
  • Sure...why not? Of course you can do it with JSON or other modern stuff. But redirecting to a jsp from a servlet and display its content after a successfull ajax call is a standard way - IMHO. – sk2212 Jul 17 '13 at 09:32

1 Answers1

1

When you call a servlet via AJAX, you stay on the same page by definition, regardless of the headers sent by the server.

If you want to change the page, you must do it with javascript, in the success handler function for the $.ajax(..) call.

You can read the Location response header and set the window.location.href to that value. See here for other options.

Community
  • 1
  • 1
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140