Post Data From Ajax or JQuery to Servlet or Database in Java

We are going to to develop web application using jsp with java servlet using ajax and jquery, there are some times you must have to pass data from jquery or ajax to servlet and save the data in to database for future update purpose.

In JS file, you must have to add this code,

Here is the data in json data: and set the id of getting from json data when button click, its assign dynamically to button according to json data.

<button id=\"showComment\" class=\"btn btn-default\" data-postid=\""+ JSON.parse(data)[i].postid     

Here is the maincontainer is div and button postButton in inside the maincontainer. and  url:/Test/CommentServlet where Test is the application name and CommentServlet is the servlet name. and data is the post data in "postid": postid.

$("#mainContainer").on("click", "#PostButton", function() {
   var postid = $(this).data("postid");
   var my = $(this);
    "type" : "POST",
   }).done(function(response) {
     $(".alert-success").show("slow").html("Like Sucessfully");



How to get data in servlet, in above we can get data which is postid in our case.

public class Like extends HttpServlet {
 private static final long serialVersionUID = 1L;
 PostService postService=new PostService();
    public Like() {
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  int userid=1;
  int postid=Integer.parseInt(request.getParameter("postid"));
//just like postid, get the other things 
//We have post id here, save here comment in to database 


No need to servelt mapping in web.xml with url mapping. if you want to mapping then please don't forget to mention the corrent url in jquery file.

Happy coding !!!