Press enter to see results or esc to cancel.


Java JSP Javascript – Submit form without reloading page

In this video I have shown how to submit a form from a JSP page without refreshing the page. This is purely on Javascript and will work on any HTML supported platforms like PHP, .Net etc. This project is demonstrated in Eclipse IDE with Tomcat server.

1. Project Structure in Eclipse IDE.


2. index.jsp holds the HTML form for submitting the data to the input.jsp. Internally the form data is collected by the javascript side of the page and submitted to input.jsp without refreshing the page.

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
 function take_values(){
 var n=document.forms["myform"]["name"].value;
 if (n==null || n=="") {
 alert("Please enter User Name");
 return false;
 }else{
 var http = new XMLHttpRequest();
 http.open("POST", "http://localhost:8080/Submit_Form/input.jsp", true);
 http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
 var params = "param1=" + n; // probably use document.getElementById(...).value
 http.send(params);
 http.onload = function() {
 alert(http.responseText);
 }
 } 
 } 
</script>
</head>
<body>
<center>
<form name="myform" >
 Name <input type="text" name="name">
<br>
<input type="button" value="Submit" onclick="return take_values()">
</form>
</center>
</body>
</html>

3. input.jsp holds code to collect the parameters forwarded from index.jsp and insert into table.
input.jsp

<%@page import="java.sql.Statement"%>
<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%> 
<%
String name=(String)request.getParameter("param1");
out.println(name+" Added Succesfully");
Connection connection=null; 
try { 
 Class.forName("com.mysql.jdbc.Driver"); 
 connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "root");
 String query="insert into codes(name) values('"+name+"')";
 Statement st=connection.createStatement();
 st.executeUpdate(query);
} catch (ClassNotFoundException e) {
 e.printStackTrace();
} catch (SQLException e) {
 e.printStackTrace();
}
%>

4. After running the project in local host server. The index.jsp will be looking like,

5. After successful insertion the alert will be generated from input.jsp and it will be displayed in index.jsp

6. MySql table after insertion of data in the table.

Download the project here.

Submit_Form.rar