Search code examples
javaajaxservletsaem

Unable to send json data to Java servlet using AJAX


I am trying to pass json data of a datatable and the email the user inputs to my java servlet. I get a status 200 but no data response. I have my AJAX code here:

$.ajax({
  url: "/bin/abc/sendrohssearchresult",
  type: "POST",
  contentType: "application/json",
  data:{
     "email": email,
     "emailSubject": emailSubject
  },
  success: function(status){
      console.log("success",status);
  },
  error:function(error){
      console.log("error",error);
  },
})

And my Java servlet:

@Component(service= Servlet.class,
        property={
                Constants.SERVICE_DESCRIPTION + "=Send Email of RoHS Search Results",
                "sling.servlet.methods=" + HttpConstants.METHOD_POST,
                "sling.servlet.paths="+ "/bin/abc/sendrohssearchresult"
        })
public class RohsEmailServlet extends SlingAllMethodsServlet {

    @Override
    protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
        String email = request.getParameter("email");
        String emailSubject = request.getParameter("emailSubject");
    }

}

I have tried other solutions I've found here on stackoverflow such as JSONify the data, remove dataType: json, and adding contentType: application/x-www-form-urlencoded; charset=UTF-8; but still the same result. I am using AEM.


Solution

  • As @rakhi4110 mentioned, I needed to add response.getWriter() in order to receive a data response. So I added:

    response.getWriter().write("Success Data");