Ajax with Spring MVC not working - java

This is my jsp from where I try to inser the user
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Add Users using ajax</title>
<script src="/Spring3MVC/js/jquery.js"></script>
<script type="text/javascript">
function doAjaxPost() {
// get the form values
var firstName = $('#firstName').val();
var lastName = $('#lastName').val();
$.ajax({
type: "POST",
url: "/insert",
data: "firstName=" + firstName + "&lastName=" + lastName,
success: function(response) {
// we have the response
$('#info').html(response);
$('#firstName').val('');
$('#lastName').val('');
},
error: function(e) {
alert('Error: ' + e);
}
});
}
</script>
</head>
<body>
<h1>Add Person</h1>
<table>
<tr><td>First Name : </td><td> <input type="text" id="firstName" name="firstName" /><br/></td></tr>
<tr><td>Last Name : </td><td> <input type="text" id="lastName" name="lastName" /> <br/></td></tr>
<tr><td colspan="2"><input type="button" value="Add Users" onclick="doAjaxPost()"><br/></td></tr>
<tr><td colspan="2"><div id="info" style="color: green;"></div></td></tr>
</table>
Show All Users
</body>
</html>
And this is my controller code
#RequestMapping(value="/insert", method = RequestMethod.POST)
public String insertPerson(ModelMap model, HttpServletRequest request, HttpServletResponse response, #RequestParam("firstName") String firstName, #RequestParam("lastName") String lastName ) {
personDao.savePerson(firstName,lastName);
model.addAttribute("nameAdded", firstName+" "+lastName);
return "personAdded";
}
When I click the 'Add Users' button, nothing happens. Can anyone please help me in fixing this?

You are using contextual URLs everywhere except the Ajax post.
Should
url: "/insert",
maybe be
url: "/SpringMVC/insert",
or even better
url: "<spring:url value='/insert' />",

Try
data: {firstName: firstName, lastName: lastName},
instead of
data: "firstName=" + firstName + "&lastName=" + lastName,
in your ajax call.

Use the url in JSP for AJAX request as:
url: "insert"
in place of:
url: "/insert"
You are using absolute URL which is pointing to the root of the server and not to your controller.
I have tested it and it's working fine for me with your code.

what is the absolute url for the two pages, and if you hit f12 key on you keybourd you can trace the ajax call and trace the response code, if it's 200 it's ok nothing wrong with your server side code now check the success function otherwise check the server code and ofcourse 404 means it didn't reach the server.

Related

unable to send "JSON.stringify" data to servlet [duplicate]

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 6 years ago.
I am not able to send data in JSON format from my jsp to servlet controller. I think, I am somewhere wrong in my ajax call to servlet. Below is my code:
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 src="js/jquery.min.js" type="text/javascript"></script>
<script>
var SendInfo=[];
$(document).ready(function(){
$("#but").click(function(){
$(".tabclass tr td input[type='checkbox']:checked").each(function(){
var sibs=$(this).parent().siblings("td");
var v0= $(this).val();
var v1=$(sibs[0]).text();
var v2=$(sibs[1]).children("select[name='address']").val();
var domain = {
id:v0,
name: v1,
address: v2
}
SendInfo.push(domain);
alert(v0+" & "+v1+" & "+v2);
});
$.ajax({
type: "POST",
url: "s1.do",
data: JSON.stringify({ students: SendInfo }), // might be wrong here or is it correct way to send data?
success: function(data, status){
alert("Data: " + data + "\nStatus: " + status);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
});
});
</script>
</head>
<body>
<table border="1" class="tabclass">
<th>select</th><th>Name</th><th>Address</th>
<tr>
<td><input type="checkbox" name="selectCheck" class="select" id="ch1" value="1"/> </td>
<td><span class="name">Nitin</span></td>
<td><select name="address">
<option>Gurgaon</option>
<option>Noida</option>
<option>Rohini</option>
</select></td>
</tr>
<tr>
<td><input type="checkbox" name="selectCheck" class="select" id="ch2" value="2"/> </td>
<td><span class="name">Abc</span></td>
<td><select name="address">
<option>Gurgaon</option>
<option>Noida</option>
<option>Rohini</option>
</select></td>
</tr>
<tr>
<td><input type="checkbox" name="selectCheck" class="select" id="ch3" value="3"/> </td>
<td><span class="name">Xyz</span></td>
<td><select name="address">
<option>Gurgaon</option>
<option>Noida</option>
<option>Rohini</option>
</select></td>
</tr>
</table><br><br>
<button id="but">Test</button>
<br></br><button id="but2">Test2</button>
</body>
</html>
Servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String abc = request.getParameter("students");
System.out.println("JSON > "+abc);
}
I am getting the output in console as :
JSON > null
I just needed to change data element of ajax call to :
data: {students : JSON.stringify(SendInfo)},
request.getParameter() reads data from the URL (query parameters) or form posted parameters (application/x-www-form-urlencoded, multipart/form-data content type).
If you post JSON you have to read it from the servlet inputStream (request.getInputStream), and parse the string.

The request sent by the client was syntactically incorrect. using #RequestParam in spring

I am new to Spring MVC. I made a simple form when button is clicked the form values send to the controller and set in the second view. But when i click the button it is giving me the error
The request sent by the client was syntactically incorrect.
Here is my code:
Controller:
#Controller
#RequestMapping(value="/admissionform")
public class StudentAdmissionController {
#RequestMapping(value="/form.html", method = GET)
public ModelAndView getStudentForm() {
ModelAndView model = new ModelAndView("StudentForm");
return model;
}
#RequestMapping(value="/submit.html", method = POST)
public ModelAndView submitStudentForm(#RequestParam("name") String name,
#RequestParam("password") String password) {
ModelAndView model = new ModelAndView("SubmitForm");
model.addObject("msg", "Name is : "+name + " Password is : " + password);
return model;
}
}
StudentForm:
<%# 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>
<title>Student Form</title>
</head>
<body>
<div class="modal-body" id="main-body">
<form action="submit.html" method="post">
<div>
<label>Email address:</label>
<input class="form-control" id="email" name="email">
</div>
<div >
<label for="pwd">Password:</label>
<input id="pwd" name="password">
</div>
<input type="submit" value="Submit"/>
</form>
</div>
</body>
</html>
SubmitForm:
<%# 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>
<title>Form Submitted</title>
</head>
<body>
<div>${msg}</div>
</body>
</html>
Tell me what is the mistake that i am doing in the code. I shall be thankful :)
By default parameters annotated with #RequestParam are mandatory. So, those parameters should be present in client requests. In your submitStudentForm method you have two required parameters named name and password:
#RequestMapping(...)
public ModelAndView submitStudentForm(#RequestParam("name") String name,
#RequestParam("password") String password) { ... }
Then you should pass those parameters with the exact same names in your from. Currently, you're passing the password parameter:
<div>
<label for="pwd">Password:</label>
<input id="pwd" name="password">
</div>
But failing to do so for the unfortunate name parameter. I guess you should rename the email parameter to name:
div>
<label>Email address:</label>
<input class="form-control" id="email" name="name">
</div>
For more info, you can checkout the Spring documentation.

Sending form in json to servlet and doing validation

So i have this form with user name and password. I need to convert the form data in json and send it to a servlet, unpack the data do the validation and return the result back in json format to the browser. At the browser end i need to unpack and show the result.
Okay, so far i have written code to generate a json object from the form and send it to the servlet. Now i need help in receiving it at the servlet end to do validation.
<%# 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 src="js/jquery-1.11.2.js"></script>
<script>
function sendrequest()
{
var fname= document.getElementById("Fname").value;
var password= document.getElementById("pass").value;
alert("inside function" + fname+" "+password);
var jsonstring="{\"fname\":\""+fname+"\",\""+"password\":\""+password+"\"}";
//var jsonstring='{"fname":'+fname+"\",\""+"password:"+password+"}';
alert(" jsonstring " + jsonstring);
document.getElementById("mesg").innerHTML=jsonstring;
var obj = JSON.parse(jsonstring);
$.ajax({
url: 'Chk',
type: 'GET',
data: {jsons: obj},
error: function() {
document.getElementById("mesg").innerHTML="there is error";
},
dataType: 'text',//'json'
success: function(data) {
document.getElementById("mesg").innerHTML="working";
alert("working");
document.getElementById("mesg").innerHTML=data;
}
});
}
</script>
</head>
<body>
User name:<input type="text" id="Fname" name="Fname" maxlength="12" size="12"/> <br/>
Password:<input type="text" id="pass" name="pass" maxlength="12" size="12"/> <br/>
<input type="button" value="fwd" onClick="sendrequest();"/>
<div id="mesg">252</div>
</body>
</html>
Servelet code :
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String json = request.getParameter("jsons").toString();
// 1. get received JSON data from request
}
I have looked at many example not sure how to parse this. Any help will be deeply appreciated.
I think, you can use json parse library.
JSON Simple is usually using library for parsing json string.
http://code.google.com/p/json-simple/
If you want to find any other library,
visiting "http://www.json.org/" and find text java.
You can find other libraries.

Updating database with jquery ajax for jsp

I wish to create a simple script to store information dynamically without refreshing or redirecting to another page. I've sourced high and low for answers before coming here, and I followed this.
However, I'm still unable to get it to store data because I don't know where I've goen wrong. Also, I wish to ask the purpose of success: function(msg)
Thanks a lot!
Update 1: Got it to work after following Anoop's solutions. However, such a popup appears when the data is submitted
StaffReg.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Staff Registration</title>
</head>
<body>
<%-- HTTP header --%>
<%response.addHeader("Cache-Control","no-cache");
response.addHeader("Pragma","no-cache");
response.addHeader("Expires","0");
%>
<%-- Javascript --%>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#Register').click(function(e) {
e.preventDefault();
$.ajax({
url: "StaffRegAuth.jsp",
type: "post",
data: {
username: $('#username').val(),
password: $('#password').val(),
userGroup: $('#userGroup').val()
},
success: function(msg) {
alert(msg);
}
});
});
});
</script>
<%-- Main body --%>
<h1 align="center"> Account Registration: </h1>
<div align="center">
<table style="width = 30%" >
<tr>
<td> User Name: </td>
<td><input type="text" id="username"></td>
</tr>
<tr>
<td> Password: </td>
<td><input type="password" id="password"></td>
</tr>
<tr>
<tr>
<td> User Group: </td>
<td><select name = "userGroup" id="userGroup">
<option value="1">Administrator
</optin>
<option value="2">Clerk
</optin>
<option value="3">Operations
</optin>
<option value="4">Sales
</optin>
</select></td>
</tr>
<tr>
</table>
<input type="submit" value="Register" id="Register">
</div>
</body>
</html>
StaffRegAuth.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<%-- Imports --%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%#page import="javax.servlet.*" %>
<%#page import="javax.servlet.http.*" %>
<%-- HTTP header --%>
<%response.addHeader("Cache-Control","no-cache");
response.addHeader("Pragma","no-cache");
response.addHeader("Expires","0");
%>
<%-- Variables that will be written --%>
<% String sUsername = request.getParameter("username");
String sPassword = request.getParameter("password");
int sUserGroup = Integer.parseInt(request.getParameter("userGroup"));
%>
<%-- Creating new staff account - writing --%>
<%
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String conURL= "jdbc:odbc:HOD_DATA";
Connection con = DriverManager.getConnection(conURL);
Statement st = con.createStatement();
int status = st.executeUpdate("insert into Staff(username, password, user_group) values('"+sUsername+"','"+sPassword+"',"+sUserGroup+")");
if(status>0){
//out.println("Update sucessful");
}
else{
//out.println("Update unsuccessful");
}
st.close();
con.close();
}
catch(Exception e){
out.println(e);
}
%>
</body>
</html>
Remove the submit button and use a normal html button with Id as Register.
Modify your html input types and replace the name attribute with id attribute. Ex: use id="username" instead of name="username"
Debugging:
Use firebug to check what value is passed to server. Ensure the correct ajax request is submitted.
Hope it helps.

Set Ajax response on jsp not working

Last few hours i am trying to solve this but i can not.I am sending ajax request using jquery and based on response i set data on jsp.actully i am checking login detail so if login fail it set error message on label problem is that error message is set for few second and removed i mean to say error message is set for few second i want that if login fails the message is set on label still user enter valid details
thanks in advance
Here is my code
LoginDemo.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">
<link href="css/firstpage.css" rel="stylesheet" type="text/css" /><!-- <style> -->
<script src="js/jquery.min.js"></script>
<title>Insert title here</title>
<script>
$(document).ready(function(){
$("#submit").click(function(){
$.ajax({
type: "POST",
url: "AddInspServlet",
cache:false,
data: { userid: $('#username').val(), password: $('#password').val(),btn:$('#submit').val() },
success:function(data,textstaus){
alert("success:"+data);
if(data == "no"){
alert( document.getElementById("error").innerHTML);
document.getElementById("error").innerHTML= "UserName OR Password is incorrect";
alert( document.getElementById("error").innerHTML);
}else{
location.href = 'Home.jsp';
}
},
error:function(data){
alert("error"+data);
},
});
});
});
</script>
</head>
<body>
<form id="login" name="Loginform" method="post">
<h1><b>Log In</b></h1>
<fieldset id="inputs">
<input id="username" type="text" placeholder="Username" autofocus required>
<input id="password" type="password" placeholder="Password" required>
</fieldset>
<fieldset id="actions">
<input type="submit" id="submit" value="login">
Forgot your password?
</fieldset>
<label id="error" style="color: red;font: bolder; font-size: 18px;">
</label>
</form>
</body>
AddInspServlet
Here i m adding code which server executed and retrieve response
if(btn.equals("login"))
{
System.out.println("***** login condition checking ******");
String password =request.getParameter("password");
UserVO v =op.loginCheck(username, password);
if(password.equals(v.getPassword()))
{
System.out.println("inside true condition");
HttpSession session = request.getSession();
session.setAttribute("userid",v.getUser_id());
session.setAttribute("username",v.getUsername());
session.setAttribute("user", v.getFirst_name()+" "+v.getLast_name());
session.setAttribute("roleid", v.getRole_id());
// response.sendRedirect("Home.jsp");
System.out.println("submitting data success fully");
out.print("yes");
}
else
{
System.out.println("false condition");
out.print("no");
}
}
Get rid of the form tags.
By adding a type="submit" input element without using the action attribute in the form tag, the page will be reloaded.
Or you could keep the form tags and change the type of the submit button to type="button". The form will then not be executed and the page will not reload.
It would be better if you be more specific about the problem. I assume your problem is Label is getting displayed for few seconds and then get disappeared. Is that is true? then try to return "false" inside you data == "no" logic.
Thanks.

Categories