Submitting JSP form data to servlet with Jquery Ajax

Now days I’m working on a web project. So I decide to tell you some modern web techniques regarding Web Developing.

Now a days one of the most popular  plugin is  a Jquery plugin so in here I’m explaining how to use Jquery with Ajax.

If we want to get some data from the user in webpage the best way is to use html <form> tag but case is if we using normal Ajax we have to write long java script to handle that ajax object but if we use Jquery we have to write only few lines of code to do it .Other thing is we can send whole form using one line of code.

Lets see how to do it. This is my JSP file name is Index.jsp it has simle form and when user click calculate button result will show in result textbox without refresing a page.

Screenshot at 2013-03-11 21:31:34

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ajax with Jquery</title>
</head>
<body>
<h1>Ajax with Jquery Simple Example</h1>
<h3>madushankaperera.wordpress.com</h3>
<br>
<form name="form1" method="GET" 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><input type="submit" value="Calculate"/></td>
</tr>
<tr>
<td>Result</td><td><input type="text" value="" id="result"/></td>
</tr>
</table>
</form>
</body>
</html>
<script type="text/javascript" src="js/jq.js"></script>
<script type="text/javascript">

var form = $('#form1');
form.submit(function () {

$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
var result=data;
$('#result').attr("value",result);

}
});

return false;
});
</script>

I have use Jquery Ajax method to deal with the Ajax.First I’m getting the form element in html tag to javascript variable
called “form” then I’m passing it to my servlet using Ajax. Then getting return value from servlet and dispaly it on page

In this example getting the 2 values from the user and pass it to java servlet and calculate the sum and display it on a page

here is my Java Servlet name is “Ajaxexample.java”


package com.servlets.cal;

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 madushanka
*/
public class Ajaxexample extends HttpServlet {

@Override
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 + "");

}
}

My web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>Ajaxexample</servlet-name>
<servlet-class>com.servlets.cal.Ajaxexample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Ajaxexample</servlet-name>
<url-pattern>/Ajaxexample</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

Actually this is very easy method to submit form data with Ajax you can use this with even PHP also .

Advertisements

72 thoughts on “Submitting JSP form data to servlet with Jquery Ajax

  1. Thai Tung says:

    Thanks a lot
    I’m from VietNam and I speak and write English not good
    If I write something incorrect please forgive me 🙂
    After search in google now I know how to upload image but in my project have some problem
    that when I upload image success it display image but refresh page and all information I write in that page will lost.Can you tell me some way to fix that

    • You are welcome friend 😀 nice to meet you .It doesn’t matter because we all are not perfect 100% 😀

      The thing is HTTP is stateless protocol . It means it wont keep your data all the time.
      When you refresh the page it means you are requesting your page again but HTTP is considered that as new request there for it will show you a clean page without your old data.

      If you want to refresh part of your page without refreshing your whole page you can use Ajax or Jquery load() method .

  2. Thai Tung says:

    Yes many people told me that i can use ajax to deal with my problem
    But I don’t know how to use ajax to load a image.I don’t know anything about ajax just a litter bit about jquery
    In my project after I finish upload image I save image name in seesion.Can you tell me how can I display image from source like this

    <%
    if (session.getAttribute("imageUrl") != null) {
    out.print("New Product Image”);
    %>

    <img style='padding:10px 10px' width='100px' height='90px' src="${pageContext.request.contextPath}”/>

  3. Thai Tung says:

    yes It correct.Your comment form don’t have enough space
    <%out.print("”);%>

    But how to use ajax to avoid loading page again

  4. Jorge says:

    I pressed the button and doesn’t work, I haven’t could implemented any exercise taught on internet. I don’t know what I could be doing bad. Or Maybe Is it the JQuery library?. In this example, I press the button and appears other page with the result, but does’nt appear into the input with id=result.

    I’m working with PURE SERVLETS, no struts, no spring.

  5. e says:

    why do you use Interger.parseInt…
    Integer.parseInt(request.getParameter(“n1”));

    you can’t just go int n1 = request.getParameter(“n1”);

  6. Priya reddy says:

    Hi, i need to get a result with out any submit button.. like if user enter in number1 and number2 without clicking any button it should display the output in result field.. so please help me

    • razaractor says:

      I would suggest you use a GSON library for doing that and in you servlet have something of the following for the request:

      List people=new ArrayList();

      people.add(new Person(“sneha”,”sneha”));
      people.add(new Person(“razaractor”,”razaractor”));

      String json = new Gson().toJson(people);

      response.setContentType(“application/json”);
      response.setCharacterEncoding(“UTF-8”);
      response.getWriter().write(json);

  7. sneha says:

    I have a jsp and i need to pass a value from that jsp to servlet without submitting that form as i am opening a pop up window from that form and refreshing the parent form again after doing required action. Can somebody suggest me how to proceed…

  8. Manoj says:

    Dude… Your jquery code written in Script is not required at all and without this jquery code this code is working but result is getting displayed on other page not on same page in result field, Because you are using Action=”Ajaxexample”. I want to use Jquery Post method written in script and i dont want to use Action=”Ajaxexample” on form. I removed the action from the Form and trying to implement this post mehtod by jquery only but till now i am not able to get success. n1 and n2 values are not getting post to Ajaxexample servlet at all 😦
    Below is the function which i am using.

    $(document).ready(function() {
    $(“#Submit”).click(function () {
    alert(“inside click function”);
    $.ajax({
    url: “http://localhost:8082/JQuery_Test/AjaxExample”,
    type: “POST”,

    success: function(response) {
    return alert(“Hey”);
    },error: function(errorData){
    alert(errorData+””);
    }
    });
    alert(“Exiting”);
    } );

    Both alert are working but i checked values on Ajaxexample servlet and the n1 and n2 values are not getting posted on that servlet.
    });

    • Manoj says:

      I am wondering, if i am putting this script in head tag then result is getting displayed on new page but if i am putting this script after body tag then its giving result in the defined text box. Can anyone tell me why its behaving differently in both these cases. As per my understanding we can keep the script tag either in body or head but it should behave similar in both the cases.

  9. Hey friend , I tried your code above(copy pasted all the codes actually hihihi ), but when I tried to click the calculate button the result was displayed in the other page not the same with what’s in your video though. Please help T__T

  10. houda.talha@gmail.com says:

    Can you post the jq.js pls, cause when i click on calculate submit that display result in another page, i’m sure that i have the same code but it doesnt work.. Please help me

  11. sunil tariyal says:

    thanks sir for this article..
    but if i dont want to use jquery plug in. i want to use only ajax to submit form with both validation server and client with appropriate result on text boxes. pls suggest me is it possible or not ?

  12. Carron says:

    Hi,after i implemented your code,my page still proceed to the action url.How can I submit the form without directing my page to action url?

  13. I am new to ajax. Your code is working. Simple and Superb solution Madushanka perera!! In fact i feel you are a person of calibre and would like to offer part time work to you!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s