title: Sending JSON Object to servlet using Ajax
body: <p>I am trying to write a simple online BMI calculator, I am a beginner in using Ajax with servlet. I am trying to send JSON object to the servlet, the object looks like (it is just an example)</p>
  
  <p>{"fname":"name","lname":"lastname","email":"jh"}</p>
  
  <p>The servlet is supposed to take the weight and height and calculate BMI to return it in a response to the webpage </p>
  
  <p>after applying this code on index.jsp page</p>
  
  <p>then I handle the request in the servlet this way:</p>
  
  <pre><code>
  
  
  $(document).ready(function(){
  $("#simplepost").click(function(e)
  {
  var data = $('#ajaxform').serializeObject();
  
  
  
  $.ajax({
      type: "POST",
      url: "AddServlet",
      contentType: "application/json", 
      data: JSON.stringify(data),
      success: function(response) {
          // ...
  
      }
  });
  
  });
  });
  
  
  </code></pre>
  
  <pre><code>
  import javax.servlet.ServletException;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  
  import org.json.HTTP;
  import org.json.JSONException;
  import org.json.JSONObject;
  
  
  
  public class AddServlet extends HttpServlet  {
  
  private static final long serialVersionUID = 1L;
  
       protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
  
           JSONObject jsonObject;
  
           StringBuffer jb = new StringBuffer();
            String line = null;
            try {
              BufferedReader reader = request.getReader();
              while ((line = reader.readLine()) != null)
                jb.append(line);
  
  
            } catch (Exception e) { e.printStackTrace(); }
  
            try {
  
  
               jsonObject =  HTTP.toJSONObject(jb.toString());
  
               System.out.println("jsonObject    "+jsonObject);
               System.out.println("jb   "+jb);
  
  
  
            } catch (JSONException e) {
              // crash and burn
              throw new IOException("Error parsing JSON request string");
            }
  
  
  
       }
  }
  
  
  </code></pre>
  
  <p>I get this result on the servlet:</p>
  
  <pre><code>jsonObject  
  
    {"Request-URI":"","Method":"{\"fname\":\"name\",\"lname\":\"lastname\",\"email\":\"jh\"}","HTTP-Version":""}
  
  jb  
  
  {"fname":"kjh","lname":"jkh","email":"jh"}
  </code></pre>
  
  <p>How can I read JSON data on the Servlet to calculate the BMI?</p>
  
  <p>And how could I send the result (a number ) as a response to the web page?</p>
  
  <p>**I tried to use ObjectMapper class, I get errors, I tried to add dependencies but eclipse stops working when I try to update the indexes </p>