Send POST Request to Servlet in JQuery in One Statement!

Post request with JQuery
Here is a single-line statement to send a POST request to a servlet with JQuery. This is gonna be dead simple. Yes, so simple that it is nothing more than a JQuery method call. Curious about what the method is? Me too! It is none other than..

post(): There are a lot of versions of this method. But here, we are going to use the simple version which takes the url-pattern and the data to be submitted.

Project structure

Folder: D:\Program Files\Apache Software Foundation\Tomcat 8.0\webapps\jq_post
        +-- index.html
        +-- WEB-INF
                    +-- classes
                            +-- simple.class


        <title>Send POST Request to Servlet with JQuery</title>
        <script src=""></script>
            $( "#hform" ).submit(function(event) {
                // Stop form from submitting normally
                // Get some values from elements on the page:
                var form = $(this);
                // Get the value in input uname
                // Send the data using post
                var posting = $.post("hello",{uname:term});
                    // When the POST request is done..
                    // data: The output printed in servlet
                    posting.done(function(data) {
                        // Put the results in a div
        <!--Create the form-->
        <form id="hform" action="/jq_post/hello" method="post">
            <input type="text" name="uname"/>
            <input type="submit" value="SUBMIT"/>
        <!--Create the form-->
        <div id="view"/>

web.xml - Deployment descriptor


Related: What is web.xml in servlets? contains doPost()

import javax.servlet.http.*;
import javax.servlet.*;
public class simple extends HttpServlet
    public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
        // Get the user name from html input field
        String name=req.getParameter("uname");
        // Get PrintWriter obj using getWriter() in HttpServletResponse
        PrintWriter pw=res.getWriter();
        // Print, that's it!!
        pw.println("Hello "+name+"!");

Image credit:

Posted by at on

Tags: JQuery, Servlets,