I have used ajax with jquery and my ajax url is calling another jsp page which submits form data to database the problem is whenever I'm running the insert query, its replying "Null values can't be inserted to database" kinda exception, but whenever I'm reloading same page and clicking submit button, its getting submitted to database. I think the problem is with something like postback method, I'm new to ajax so please need your help...
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#save').click(function ()
{
$.ajax({
type: "post",
url: "test.jsp", //this is my servlet
data: "input=" +$('#id').val()+"&output="+$('#op').val(),
success: function(msg){
$('#output').append(msg);
}
});
});
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
input:<input id="id" type="text" name="" value="" /><br></br>
output:<input id="op" type="text" name="" value="" /><br></br>
<input type="button" value="save" name="save" id="save"/>
<div id="output"></div>
</body>
JSP:
<%@page import ="com.connectionUtil.ConnectionUtil"%>
<!DOCTYPE html>
<script src="js/jquery.min.js" type="text/javascript"></script>
<% String id = request.getParameter("input");
try {
Connection con = ConnectionUtil.getConnection();
String sql = "insert into test(ID,...) values ('" + id + "',...)";
PreparedStatement ps = con.prepareStatement(sql);
ps.executeUpdate();
} catch (SQLException sqe) {
out.println(sqe);
}%>
<body> <h4><%=id%> is stored </h4> </body> </html>
Sorry, I would not post this as an answer but I have to because I do not have the privilege in my account to post it as a comment but I as sure your confuse what to be click. The
#call
refers to theelement
div
not the actual button but it will work either. Can you please post yourtest.jsp
so that we can see the code because I suspect that there cause the problem.I think you had edited your question so I think my answer is a wasteful.
Your ajax code is wrong. It should be like this:
And then use the
request.getParameter("input")
to get the parameter valueUPDATE : Please note that i missed a comma (,) at the end of the line data:....
UPDATE 2 : This is a working demo of your code without the connections to db...
index.jsp:
test.jsp :
The first screen shows this:
And after inserting data and pressing
save
button it shows this: