danny.lesnik
danny.lesnik

Reputation: 18639

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?

Upvotes: 6

Views: 16552

Answers (2)

Abdel Raoof Olakara
Abdel Raoof Olakara

Reputation: 19353

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).

Upvotes: 2

WhiteFang34
WhiteFang34

Reputation: 72079

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.

Upvotes: 13

Related Questions