2

Here in the below code i want to call a servlet through ajax and then i redirect the data from servlet to jsp.ajax call to servlet is working fine but the problem is redirecting to the jsp page is not displayed in the browser and the same jsp page is displayed when i used with javascript code without ajax.

javascript ajax code in the jspfile:

function generate(){
...
...
 var url="RedirectServlet";
 var ajax=new AJAXInteraction(url,"RedirectServlet");
 var param    ="FD="+FD+"&TD="+TD+"&actionid="+status+"&usercode="+usercode+"&action=reports"+"";
 ajax.send(param);

....
 }
 function AJAXInteraction(url, actionType) {
     this.url = url;

     var req = init();
   var actionRequested = actionType;
     req.onreadystatechange = processRequest;      
    function init() {
        if (window.XMLHttpRequest) {
            return new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            return new ActiveXObject("Microsoft.XMLHTTP");
        }
     }

     function processRequest () {
        if (req.readyState == 4) {
            if (req.status == 200) {                                
                if(actionRequested=="TestDelegation") {                     
                    PostProcess1(req.responseXML);
                }

            }
        }
     }
     this.send = function(param) {
        req.open("POST", url, true);

        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        req.send(param);


     }
}//end of AJAX Interaction object.

Servlet code:

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

    response.setContentType("text/html;charset=WINDOWS-1256");
    String action=request.getParameter("action");
    System.out.println(action);

    if(action.equals("reports")){
        System.out.println("inside reports");



        //Getting values from Reports_arb.jsp
        String Fromdate=request.getParameter("FD");
        String Todate=request.getParameter("TD");
        String status=request.getParameter("actionid");
        String usercode=request.getParameter("usercode");

        //placing given values in a session 


        request.setAttribute("FD", Fromdate);
        request.setAttribute("TD", Todate);
        request.setAttribute("actionid", status);
        request.setAttribute("usercode", usercode);


        //Redirecting to showReport_arb.jsp
        //response.sendRedirect("showReport_arb.jsp");

          ServletContext sc = getServletContext();
            sc.getRequestDispatcher("/sample.jsp").forward(request, response); 
vagga ravi
  • 43
  • 1
  • 2
  • 11

2 Answers2

11

You need to understand the fact that when you send http request from ajax, it means that you are sending the request in separate thread and not in the main thread (the page itself from where you are sending the request). So redirection at the servlet will not reflect at the client end. In order to achieve this, send back the URL to which you want to redirect as a response to request and on success method of ajax simply use java script window.location(URL);

At servlet

JSONObject jobj = new JSONObject()
String urlToRedirect = "test.jsp";
jobj.put("url",urlStr);
response.getWriter().write(jobj.toString());

At client end

$.ajax({
                url: 'servletName',
                data: {
                    userID: selectedID
                },
                type: 'post',
                success: function(data){
                  window.location = data.url;
                } 

            });
Rajan Twanabashu
  • 4,586
  • 5
  • 43
  • 55
  • What if I had some data which I want to send to the jsp page ? – Abhishek Ghosh May 07 '17 at 18:26
  • @AbhishekGhosh As far as I know you can't send data to jsp if you use sendRedirect(). In the case you need to use forwarding. – Artmal Sep 18 '17 at 13:05
  • @Rajan, what is JSONObject you have mentioned about in the servlet? I intend to pass a parameter from the servlet to the jsp. – aiman Jan 18 '18 at 20:06
0

Instead of creating the request and response object, use jquery Ajax. It is very simple to use.

 /* Send the data using post and put the results in a div */

 $.ajax({
  url: "/YourServlet",
  type: "post",
  data: values,
  success: function(){
      alert("success");
       $("#result").html('submitted successfully');
  },
  error:function(){
      alert("failure");
      $("#result").html('there is error while submit');
  }   
}); 
MaheshVarma
  • 2,081
  • 7
  • 35
  • 58