0

I am sending form data using Jsp through AJAX on Servlet.
reg.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form>
        Enter name:<input type="text" id="name" /> <br />

        <button onclick="callJqueryAjax()">Save</button>
    </form>
    <span id="result"></span>

    <script
        src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        function callJqueryAjax() {
            location.reload(false);
            var name = $('#name').val();
            console.log(name);

            $.ajax({
                url : 'Save',
                method : 'POST',
                data : {
                    name : name,
                },
                success : function(resultText) {
                    $("#result").html(resultText);

                }
            });
        }
    </script>
</body>
</html>

SaveMe.java

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/Save")
public class SaveMe extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private Connection makeCon;
    private Statement stmt;

    public void init(ServletConfig config) throws ServletException {
        JdbcCon jdbcCon = new JdbcCon();
        makeCon = jdbcCon.makeCon();
        try {
            stmt = makeCon.createStatement();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {
        String name = request.getParameter("name");

        res.setContentType("text/html");

        PrintWriter out = res.getWriter();

        String sql = "insert into users (name) Values('" + name + "')";
        System.out.println(sql);

        try {

            int result = stmt.executeUpdate(sql);

            if (result > 0) {
                out.print("Inserted");

            } else
                out.print("Not Inserted");

        } catch (SQLException e) {

        }

    }

}

I receive the output in ajax but the thing is JSP gets reload by itself and removes the response as well as removes the data from Textbox from which my response gets disappear by itself.

Please provide me the solution and also a better way for writing an ajax call

1 Answers1

0

First of all I didn't understand why you are using "location.reload(false);" in your JSP page before submitting the ajax request. You could remove it. In addition a good practice when using ajax request is to specify the "dataType", in your case "html". Here is an example:

    $.ajax( {
    type : 'POST',
    url : 'SaveMe',
    success : function(result) {
      $("#result").html(result);
    },
    dataType : "html"
});
Emile ASTIH
  • 2,894
  • 2
  • 9
  • 8
  • It Should be ```url: 'Save' ``` instead of ```url : 'SaveMe'``` and after removing location.reload and applying ```dataType:"html"```, its not working. Any other solution? – Sumit Agrawal Oct 16 '20 at 08:43
  • Ok, I found the answer: you should also remove the "
    ", because that's what's causing the page to refresh.
    – Emile ASTIH Oct 16 '20 at 08:59
  • If I am going to upload any file like image or pdf what changes need to be done in Ajax script as form uses ```enctype="multipart/form-data``` and now we have removed the form tag from jsp. – Sumit Agrawal Oct 16 '20 at 11:09
  • Hello, in order to upload files without refreshing the page you need to use Ajax and not submitting a form like you were doing. Here is a link you can follow to implement it: https://stackoverflow.com/questions/2320069/jquery-ajax-file-upload – Emile ASTIH Oct 16 '20 at 13:01