1

I created a jsp page with 2 variables and using jquery that is passed to Servlet and displayed in console, now i need to pass a variable back to jquery.How to write it??Please see the servlet and js i used.

jquery

$(document).ready(function(){
$("#click").click(function(){
     var form = $('#new');
       alert("serialize :"+form.serialize());
           $.ajax({
               url: 'login',
               data: form.serialize(),
               type: 'post',
               success: function(data){ 
                   alert("Reached Servlet"+data);

               }
                   });
});
});

Servlet do post as follows

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

        System.out.println("in POST");
        String a=request.getParameter("txt_name");

        String ad=request.getParameter("txt_address");

        PrintWriter ins_writer= response.getWriter();
        System.out.println("console");
        ins_writer.write("In servlet POST > value for Name : "+a);
        System.out.println("a > "+a +">>>>>"+ad);

        System.out.println("----------------------------From Jquery-------------");

        System.out.println("Name  from JSP> "+a);
        System.out.println("Address  from JSP> "+ad);

         String pq="Amanda";       

    }

I just wanted to pass this 'pq' value to jquery ?Please help me!!

RockAndRoll
  • 2,247
  • 2
  • 16
  • 35
Priyanka U
  • 443
  • 1
  • 5
  • 8

2 Answers2

0

You can pass back a hidden element and then output it when ajax request finishes:

In servlet:

 System.out.println("<input type='hidden' id='pqId' value='"+pq+"'/>");

And then in ajax append the response to a hidden area, and get the value of the field:

$.ajax({
  url: 'login',
  data: form.serialize(),
  type: 'post',
  success: function(data){ 
    $('body').append('<div style="display:none;">'+data+'</div>');
    alert($('#pqId').val());
  }
});
MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125
0

Change System.out.println to ins_writer.write

like:

ins_writer.write("<input type='hidden' id='pqId' value='"+ad+"'/>");

and previous answer should work fine.

Rahul
  • 334
  • 1
  • 8