Newsletter

Submit Form Without Refreshing Page In Java/Jsp With jQuery

jQuery » on Sep 16, 2012 { 17 Comments } By Sivateja

Hi friends, let us see how to submit form with out page refresh in java servlets applications with jQuery api.  i believe you can follow this procedure to implement the same in struts or any MVC applications too.

submit-form-without-page-refresh-logo

submit-form-without-page-refresh

Files required

  • index.jsp
  • web.xml
  • jquery-1.4.2.min.js [ You can download from jquery.com ]
  • SaveData.java
  • DatabaseDetails.java

Web application Directory Structure:

index.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="JS/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
     $('#ibutton').click(function(e) {
     e.preventDefault();
     var ajaxdata = $("#country").val();
     var value ='county='+ajaxdata;

     $.ajax({
     url: "saveIt",
     //type: "post",
     data: value,
     cache: false,
     success: function(data) {
     $("#country").val('');
     $("#message").html(data).slideDown('slow');
     }
     });
});
});
</script>
<style>
#country{
border: 1px solid #8707c2;
}
</style>
</head>

<body>
<center>

<font face="verdana" size="4">
Submit Form With Out Page Refresh In Java/Servlets - jQuery<br><br>
</font>

   <form name="sub" action="saveIt" id="sub">
     <font face="verdana" size="2">Country:</font>
     <input type="text" name="country" id="country" size="30" />
     <input type="button" id="ibutton" value="Save"/>
   </form>

<br><font face="verdana" size="2"><div id="message"></div></font>

<br><br><img src="images/java4s.png">

</center>
</body>
</html>

Note: saveIt is servlet URL pattern.

web.xml

<web-app>
  <servlet>
    <servlet-name>abcd</servlet-name>
    <servlet-class>SaveData</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>abcd</servlet-name>
    <url-pattern>/saveIt</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

DatabaseDetails.java:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseDetails {		

	public Connection getConn() throws Exception
	{
		try
		{
		  Connection con = null;
		  Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
	          con =DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","admin");
	          return con;
		}
		catch (SQLException e)
		{
				throw e;
		}

	}

}

SaveData.java

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SaveData extends HttpServlet
{
    protected void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
	{
    	String country;
    	try{
    		PrintWriter out = res.getWriter();
    		DatabaseDetails details = new DatabaseDetails();
    		Connection con = details.getConn();
    		country = req.getParameter("county");
    		PreparedStatement ps = con.prepareStatement("INSERT INTO PLACES(countries) VALUES(?)");
    		ps.setString(1, country);
    		int rs = ps.executeUpdate();
    		if(rs >0)
                out.print("Data saved successfully....!!");
    		else
                out.print("Sorry..!! Got an exception.");
    	}catch(Exception e){
    		e.printStackTrace();
    	}

	}

}

Note: In line number 25,27 i have written out.print statements as

out.print(“<font color=#’43b200′><b>Data saved successfully….!!</b></font>”);
out.print(“<font color=#’ea0909′><b>Sorry..!! Got an exception.</b></font>”);

Which am not able to show above 🙂

Output:

Video Output:

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
- Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

17 Responses to “Submit Form Without Refreshing Page In Java/Jsp With jQuery”
  1. Yannikator says:

    Thanks a lot for this one.
    It was usefull to understand how use jQuery in order to use servlet in background process.

    Just one thing, there’s a mistake in the javascript in index.jsp:
    search : $(‘.ibutton’).click(function(e) {
    and replace by : $(‘#ibutton’).click(function(e) {

    And it Work!
    😉

  2. Java4s says:

    @Yannikator

    Awesome..!!!!!!!!
    Thanks bro, its been corrected now 😉

  3. This Website is veryusefull for beginers, thank you vey much

  4. Yes..this website is very good for Beginners..Thanks a lot.. Continue in this way..

  5. Navaneet says:

    Thanks a lot for this example, it’s so useful for first time…

  6. Prakhar says:

    can we do this using ajax, if yes then which one is better and why ?

  7. Smitha51 says:

    Really great info can be found on site.

  8. sunil tariyal says:

    these example is very helpful for us but i need a form submission example using only ajax not using jquery.
    so can u please suggest me example which is helpful for me.

  9. really good site for beginers…expecting more help from this site

  10. prasad says:

    Nice…Example..

    For example if i have 6 fields in my form, then will use
    data :form.serialize() method in ajax to send data.

    Here how do i get data in servlet.

    [I wnat to know how to send form data which contain more than one field and with out query param]….

    Thanks…..

  11. balaraju says:

    first thanks to you for providing such a good concepts with examples
    i was studied complete AJAX. It is very nice

    please provide jQuery also like AJAX (that is with complete explanations)

  12. sarikapawar says:

    Thanks A lot….this is very helpful for me
    One request please provide jQuery tutorial from basics

  13. yuvaraj says:

    please explain the flow of control in program ..briefly exaplin the javascript fuctions…please..sir

  14. Yogesh says:

    Hi.

    Its nice article.
    Will you explain what is abcd in your web.xml

  15. Dhruv says:

    I’ve put all the files in one folder. it is not working. what to do?

    • Ashish says:

      You can't put all the in folder. It is ridiculously asked.
      Just look at the strudefined in the image up at the top of this web page. And structure your Eclipse with this xml Java jsp files .
      May be able to get solution.

  16. Aniket Chavan says:

    plz add more topics

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2018 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.