PeakGen
PeakGen

Reputation: 23035

Unable to send form data to servlet using Ajax/JQuery without refreshing the page

I am trying to send some data from a Form to a Servlet using Ajax/JQuery without refreshing the page. Below is my JSP page.

<%-- 
    Document   : index
    Created on : Feb 23, 2015, 8:18:52 PM
    Author     : Yohan
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
   var form = $('#customItemForm');
  function formSubmit(){

 $.ajax({
     url:'SampleServlet',
     data: $("#customItemForm").serialize(),
     success: function (data) {

    }
});
}
</script>
    </head>
    <body>
        <form method="get" action="SampleServlet" id="customItemForm">
            Name <input type="text" name="name">
        <button onclick="formSubmit()">Submit</button>
        </form>
    </body>
</html>

Below is my servlet.

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Yohan
 */
public class SampleServlet extends HttpServlet {



    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            String str = request.getParameter("name");
            System.out.println(str);
        } finally {
            out.close();
        }
    }


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }


    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

However my form is always being submitted to the servlet, leaving the JSP page. What have I done here wrong?

Upvotes: 0

Views: 1292

Answers (1)

SeriousDron
SeriousDron

Reputation: 1346

As far as I can see you just don't prevent default action for pushing submit button in form. Also your code will not work if user uses Enter button into field to send form, not push button with mouse

Try to use next construction

<form method="get" action="SampleServlet" id="customItemForm"  onsubmit="formSubmit(); return false;">
    Name <input type="text" name="name">
    <button>Submit</button>
</form>

Upvotes: 1

Related Questions