2

I am having an ajax call to a jsp page which in turn is redirecting depending on the value of a flag variable being calculated in that jsp file.

ajax call is something like this :

$.ajax({
            url: 'uploadwebcamimage.jsp',
            type: "POST",

            data: {
                encodeimg: dataUrl,
                OwnerId: document.Clickpictures.OwnerId.value,
                OwnerPhone: document.Clickpictures.OwnerPhone.value,
                mobilepass: document.Clickpictures.mobilepass.value,
                emailpass: document.Clickpictures.emailpass.value,
                mypassword: document.Clickpictures.mypassword.value,
                mygroupuserid: document.Clickpictures.mygroupuserid.value

            },
            error : function(){ 
                alert('Error'); 
            },
            success: function(msg){
                //alert((msg));
                    if(msg.indexOf("true")>=0)
                    {
                        //how to get grouplist 
                        location.href="site_index_groupadmin.jsp?res1="+grouplist;  
                    }
                    else{
                        alert("UNSUCCESSFUL");
                    }
            }
        });

And in jsp i did something like this :

<%
    ArrayList<String> list = new ArrayList<String>();

     String query="Select GNAME from tbGroup";
     ps1 = con.prepareStatement(query);
     rs1=ps1.executeQuery();
     while(rs1.next()){
         list.add(rs1.getString("GNAME"));
      }
    //How can i send this list also to my ajax call.Please help

    if(flag==true){

    out.println(flag);

    }

    else if(flag==false){

    out.println(flag);


    }%>

But its not redirecting to other page.Please help

user3522121
  • 215
  • 3
  • 10
  • 23
  • use jquery to get form field values or use `serialize()` and don't use `sendRedirect()` in other jsp, instead redirect in same page where you making ajax call. – Abhishek Nayak Apr 22 '14 at 10:30
  • @Rembo Though i solved the problem for redirecting.The problem Now is that i need to send an arraylist as an reuqest parameter.Please see my edited post – user3522121 Apr 22 '14 at 11:06

2 Answers2

1

When you call a jsp 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.

Get PrintWriter object by calling HttpServletResponse#getWriter and write your String.

response.getWriter().write("{isSuccess: true}");

now in jsp check isSuccess is true or false and use window.location.href

Community
  • 1
  • 1
Sanjay Rabari
  • 2,091
  • 1
  • 17
  • 32
  • actually i was trying to do that also.What i was trying is to get that flag value in my ajax call and then make decision their.Can it be done ? – user3522121 Apr 22 '14 at 09:59
  • you just write you response back with some variable value and then you will able to determine – Sanjay Rabari Apr 22 '14 at 10:00
  • Please provide me piece of code to do the same.In actual i want is that if flag is true then redirect to other page otherwise stay on the same page (here same page is the page that is making the ajax call). – user3522121 Apr 22 '14 at 10:01
  • i did not get you.please provide code for ajax call also – user3522121 Apr 22 '14 at 10:10
  • Please see my edit in post.I resolved the problem of redirecting.But face anther problem.Please help – user3522121 Apr 22 '14 at 11:10
0

How can i send this list also to my ajax call.

use Gson or any other json library to write json response do like:

<%@ page language="java" contentType="application/json; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
  //after generating your list

  Gson gson = new Gson();
  JsonObject root = new JsonObject();
  root.addProperty("flag", flag); //add flag
  root.addProperty("list", gson.toJson(list)); //add list

  out.println(gson.toJson(root));
  out.flush();
%>

and render list in ajax like:

$.ajax({
        url: 'uploadwebcamimage.jsp',
        type: "POST",
        dataType: 'json', //set dataType as json i.e. response data format 
        data: {
            encodeimg: dataUrl,
            OwnerId: document.Clickpictures.OwnerId.value,
            OwnerPhone: document.Clickpictures.OwnerPhone.value,
            mobilepass: document.Clickpictures.mobilepass.value,
            emailpass: document.Clickpictures.emailpass.value,
            mypassword: document.Clickpictures.mypassword.value,
            mygroupuserid: document.Clickpictures.mygroupuserid.value

        },
        error : function(jqXHR, textStatus, errorThrown){ 
            alert(textStatus+' : '+ errorThrown);
        },
        success: function(response){
           alert(response.flag);
           $.each(response.list, function(key,value){
               alert(value);
           });
        }
    });

Edit:

As per your comment:

create a servlet instead of writing java code in jsp, and move java codes to servlets like:

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

    ArrayList<String> list = new ArrayList<String>();

    String query="Select GNAME from tbGroup";
    ps1 = con.prepareStatement(query);
    rs1=ps1.executeQuery();

    while(rs1.next()){
         list.add(rs1.getString("GNAME"));
    }

    //set flag
    boolean flag = true;

    Gson gson = new Gson();

   response.setContentType("application/json");
   response.setCharacterEncoding("UTF-8");          
   PrintWriter out = response.getWriter();    

   out.write(gson.toJson(new ResponseResult(flag, list)));     
   out.flush();
}

and ResponseResult class looks like:

public class ResponseResult {

    private boolean flag;
    private List<String> list;

    public ResponseResult(){}

    public ResponseResult(boolean flag, List<String> list) {
        super();
        this.flag = flag;
        this.list = list;
    }

       //getters and setters
}

if you want to send list to any other jsp, then in servlet do like:

using request if you do forward:

   request.setAttribute("list", list);
   RequestDispatcher dispatcher = request.getRequestDispatcher("pagename.jsp");
   dispatcher.forward(request, response);

or alternate is using session if you do redirect then like:

//add list to session
request.getSession().setAttribute("list",list);
//get it back in another page like
List<String>myListObject=(List<String>) request.getSession().getAttribute("list");
Abhishek Nayak
  • 3,732
  • 3
  • 33
  • 64
  • I need to pass this list to this jsp page.How can i send it?Also how will i retrieve it on that site_index_groupadmin page?Also i need to do this if the flag is set to true.So do mention that also in your code.So i request you to please update your ajax call success part – user3522121 Apr 22 '14 at 11:54
  • @user3522121 if you want to send list to `site_index_groupadmin.jsp` then use `request.setAttribute("list", list);` then forward it. or better use servlets instead of jsp. – Abhishek Nayak Apr 22 '14 at 11:58
  • Also in this part : root.addProperty("list", list); its giving an error that no suitable method found for addProperty(java.lang.String,java.util.ArrayList – user3522121 Apr 22 '14 at 12:03
  • And to retrieve it on other end.Will ArrayList list1 = (ArrayList)request.getAttribute("list"); work ?Where to write this : request.setAttribute("list", list);?Will i have to write it in ajax. – user3522121 Apr 22 '14 at 12:04
  • that error is now removed and problem is just on ajax call side – user3522121 Apr 22 '14 at 12:07
  • Please update your ajax part in solution.Am not getting it clearly – user3522121 Apr 22 '14 at 12:07
  • Also i checked for your code and it gives me error alert message in ajax call not success – user3522121 Apr 22 '14 at 12:17
  • @user3522121 i have given you a sample code how to do, you should make changes as per your requirement, check now answer updated – Abhishek Nayak Apr 22 '14 at 12:19
  • Its giving an error that parse error:Syntaxerror.JSONparsse : unexpected character – user3522121 Apr 22 '14 at 12:29
  • I resolved that error.It was silly mistake.But problem remains is that how to send this array obtained to required jsp?Also as this array is bit different how to get true array values from it – user3522121 Apr 22 '14 at 12:37
  • What about success part of ajax then,?Is it not needed?If flag is false then i need to stay on the same page .Where are you checking that? – user3522121 Apr 22 '14 at 13:54
  • Do you think forwarding here only what is the requirement.?I mean where should these lines be written RequestDispatcher dispatcher = request.getRequestDispatcher("pagename.jsp"); dispatcher.forward(request, response); – user3522121 Apr 22 '14 at 13:56
  • @user3522121 in servlet put these line in last of `doGet()` or `doPost()`. – Abhishek Nayak Apr 22 '14 at 14:49