Menu



Insert data using ajax and JSP Java


Here we using 2 files for insert data in MySQL Database using Ajax:

  1. index.html:for getting the user data
  2. save.jsp: A JSP file that process the request

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>new registration</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form method="post"><br><br>
First name :<input type="text" name="fname" id="fname"/><br><br>
Last name :<input type="text" name="lname" id="lname"/><br><br>
Email :<input type="text" name="email" id="city_name" /><br><br>
User name :<input type="text" name="email" id="email"/><br><br>
<input type="submit" value="submit" id="save_data"/>
</form>
<script>
$(document).ready(function() {
$("#save_data").click(function() {
alert("succeess");
$.ajax({
url: "save.jsp",
type: "post",
data: {
fname:$('#fname').val(),
lname:$('#lname').val(),
city_name:$('#city_name').val(),
email:$('#email').val(),
success : function(data){
alert(data);
}
}
});
});
});
</script>
</body>
</html>

save.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.*,java.util.*"%>

<%
String first_name=request.getParameter("fname");
String last_name=request.getParameter("lname");
String city_name=request.getParameter("city_name");
String email=request.getParameter("email");
try
{

Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "");
Statement st=conn.createStatement();
int i=st.executeUpdate("insert into users(fname,lname,city_name,email)values('"+first_name+"','"+last_name+"','"+city_name+"','"+email+"')");
out.println("Data is successfully inserted!");
}
catch(Exception e)
{
System.out.print(e);
e.printStackTrace();
}
%>