Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Post to Servlet

I have the following code on client side:

      <script src="http://code.jquery.com/jquery-1.5.js"></script>
   <script>
    $(document).ready(function() {
   $("a").click(function() {
   //var orderId =  $("#orderId").val();
   $.post("test", { orderId : "John"},
   function(data) {
     alert("Data Loaded: " + data);
   });
   });
 });
    </script>

Server side:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        PrintWriter writer =  response.getWriter();
        try{
           String orderId = request.getAttribute("orderId").toString();
           writer.write(orderId);
           writer.close();
           }
       catch(Exception ex)
      {
      ex.getStackTrace();
      }
    }

my

request.getAttribute("orderId")

is null and I'm getting null reference exeption. What am I doing wrong?

like image 911
danny.lesnik Avatar asked Mar 24 '11 09:03

danny.lesnik


2 Answers

I think you want request.getParameter("orderId"). Attributes are only for server side use while processing the request. Parameters contain request data from the client side.

like image 107
WhiteFang34 Avatar answered Oct 07 '22 15:10

WhiteFang34


You should use getParameter method instead of getAttribute.

request.getParameter("orderId")

getParameter() will retrieve a value that the client has submitted. Where as you should use getAttribute() when you submit the request to another resource (server side).

like image 43
Abdel Raoof Olakara Avatar answered Oct 07 '22 15:10

Abdel Raoof Olakara