Submit form to servlet using JQuery Ajax
Solution 1
You have clearly written " onclick="form1.submit()">" that's why form is submitting....
Remove onClick() method from submit &
<span id="calc">Calculate</span
& replace
form.submit(function () {
line by
$( "#calc" ).click(function(){
Solution 2
<span onclick="formSubmit();">Calculate</span>
function formSubmit(){
$.ajax({
url:'localhost:8080/Ajax/Ajaxexample',
data: $("#form1").serialize(),
success: function (data) {
$('#result').html(data);
}
});
}
Solution 3
you form method is post <form name="form1" method="POST" action="Ajaxexample" id="form1">
but you are writing codes in servlet doGet()
so you may not proper results.Remeber that if the form method is get
then in the servlet doGet()
will be called and if the form method is post
then in servlet doPost()
will be called
CY5
Updated on December 14, 2020Comments
-
CY5 over 3 years
How can we submit Form to servlet when we click on span tag using Jquery Ajax, and get output from servlet? Below is calculator example code. If instead of span if i use input type="submit" i get the right result in index.html, but if i use span instead of input type for submit, i am directed to servlet page.
index.html
<form name="form1" method="POST" action="Ajaxexample" id="form1"> <table> <tr> <td>Number 1</td><td><input type="text" name="n1"/></td> </tr> <tr> <td>Number 2</td><td><input type="text" name="n2"/></td> </tr> <tr> <td></td><td><span onclick="form1.submit()">Calculate</span></td> </tr> <tr> <td>Result</td><td><input type="text" value="" id="result"/></td> </tr> </table> </form> <script src="script/jquery-1.10.2.min.js"></script> <script type="text/javascript"> var form = $('#form1'); form.submit(function () { $.ajax({ type: form.attr('method'), url: form.attr('action'), data: value, success: function (data) { var result=data; $('#result').attr("value",result); } }); return false; }); </script>
Ajaxexample.java
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); int n1 = Integer.parseInt(request.getParameter("n1")); int n2 = Integer.parseInt(request.getParameter("n2")); out.println(n1 + n2 + ""); } }
web.xml
<display-name>Ajax</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>Ajaxexample</servlet-name> <servlet-class>Ajaxexample</servlet-class> </servlet> <servlet-mapping> <servlet-name>Ajaxexample</servlet-name> <url-pattern>/Ajaxexample</url-pattern> </servlet-mapping>