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

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.

Related

How to encode field entities in URL in Spring MVC?

I made a form submit application via Spring MVC. After submitting the form, all values of input fields are visible in url.
let's suppose that after submitting the generated URL is this:
SpringTuto/successA?name=FirstUser&designation=Student&country=XYZ&dob=2018%2F01%2F16&skills=paragliding&address.street_name=avenue+Road&address.city=New+City&address.district=New+District&address.pin_code=322343
From the above url, I want to encode name, designation, country and all other parameters in some encrypted code.
After reading a few articles, i came to an understanding that I will use the URIeditor(org.springframework.beans.propertyeditors.URIEditor) to encode. But I don't know how to use it. If anyone has another way to do this please share it.
Thanks in advance.
Here is my Controller Class.
#Controller
public class SpgController {
#ModelAttribute("header")
public Model addHeader(Model view) {
int a = 10;
return view.addAttribute(a);
}
#InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/mm/dd");
binder.registerCustomEditor(Date.class, "dob", new CustomDateEditor(dateFormat, false));
binder.registerCustomEditor(String.class, "name" , new NamepropertyEditor());
}
#RequestMapping("/main")
public ModelAndView go() {
ModelAndView view = new ModelAndView("main");
return view;
}
#RequestMapping(value = "/successA", method = RequestMethod.GET)
public ModelAndView method(#Valid #ModelAttribute("bean") Bean bean, BindingResult result ) {
if (result.hasErrors()) {
ModelAndView view = new ModelAndView("main");
return view;
}
ModelAndView view = new ModelAndView("successAnother");
return view;
}
}
Here is the successAnother.jsp page
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form >
Name: ${bean.name}<br/>
Designation: ${bean.designation}<br/>
DoB: ${bean.dob}<br/>
Skills: ${bean.skills}<br/>
Street: ${bean.address.street_name}<br/>
City: ${bean.address.city}<br/>
District: ${bean.address.district}<br/>
PinCode: ${bean.address.pin_code}<br/>
Country: ${bean.country}<br/>
</form>
</body>
</html>
Here is main.jsp(Application form)
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://www.springframework.org/tags" prefix = "spring" %>
<!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=UTF-8">
<title>Spring</title>
</head>
<body>
English|French|Hindi
<h3>${msg}</h3>
<form:errors path = "bean.*"/>
<form action="successA" method="get">
<table>
<tr>
<td><spring:message code = "label.userName"/><input type="text" name="name">
</td>
</tr>
<tr>
<td><spring:message code = "label.userDesignation"/><input type="text" name="designation">
</td>
</tr>
<tr>
<td><spring:message code = "label.userCountry"/><input type="text" name="country">
</td>
</tr>
<tr>
<td>
<spring:message code = "label.userDoB"/><input type= "text" name = "dob" >
</td>
</tr>
<tr>
<td>
<spring:message code = "label.Skils"/><select name = "skills" multiple >
<option value= "driving">Driving</option>
<option value = "diving">Diving</option>
<option value = "swimming">Swimming</option>
<option value = "paragliding">Paragliding</option>
</select>
</td>
</tr>
<tr>
<td>
<h5><spring:message code = "label.userAddress"/></h5>
<spring:message code = "label.userStreetname"/><input type = "text" name = "address.street_name">
<spring:message code = "label.userCity"/> <input type = "text" name = "address.city">
<spring:message code = "label.userDistrict"/><input type = "text" name = "address.district">
<spring:message code = "label.userPin"/><input type = "text" name = "address.pin_code">
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td><input type="submit" value=<spring:message code = "label.userSubmit"/>></td>
</tr>
</table>
</form>
</body>
</html>
If your application supports HTTPS, then it can be achieved easily using spring security by doing some configuration as follows.
<http>
<intercept-url pattern="/**" access="ROLE_USER" requires-channel="https"/>
...
</http>
Integrating spring security with spring mvc is very simple.

Drop down list is not getting displayed with spring mvc and jsp

I have an application where in a JSP page i am displaying a drop down list but i am getting an exception in my code.
public class ExpenseCreationBean {
private String color;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
Controller Class:-
#RequestMapping(value = "/addDetails", method = RequestMethod.GET)
public String getExpenseEntryPage(Model model) {
ExpenseCreationBean expenseCreationBean = new ExpenseCreationBean();
model.addAttribute("expenseCreationBean", expenseCreationBean);
List<String> coloursList = new ArrayList<String>();
coloursList.add("red");
coloursList.add("green");
coloursList.add("yellow");
coloursList.add("pink");
coloursList.add("blue");
model.addAttribute("colours", coloursList);
System.out.println("I was here!!");
return "addDetails";
}
addDetails.jsp Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<html>
<head>
<title>Add Details</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function() {
$("#datepicker").datepicker({
showOn : "button",
buttonImage : "images/calendar.png",
buttonImageOnly : true,
buttonText : "Select date"
});
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<h1>Expense Entry Details</h1>
<form:form method="post" action="savedata" modelAttribute="expenseCreationBean">
<table border="6px" cellspacing="10px" cellpadding="10px">
<tr>
<td>Date Of Purchase: <input type="text" id="datepicker"
name="date_of_purchase"></td>
<td>Item Name:<input type="text" name="description"></td>
<td>Please select:</td>
<td><form:select path="color">
<form:option value="" label="...." />
<form:options items="${colours}" />
</form:select>
</td>
<td>Paid By: <select name="paid_by"></td>
<td>Amount Paid:<input type="text" name="total_price"
id="total_price"></td>
<td>Quantity:<input type="text" name="quantity_purchased"></td>
<td>Unit:<input type="text" name="unit"></td>
</tr>
<tr>
<tr>
<tr>
<tr>
<td>Exclude:</td>
<td><input TYPE="checkbox" name="exclude">
</tr>
<tr>
<td>Comments:<textarea rows="3" cols="25" name="comments"></textarea>
</td>
</tr>
<tr>
            
<td><input type="submit" value="Save" align="middle"></td>
</table>
</form:form>
</body>
</html>
I am getting the below exception :-
javax.servlet.jsp.JspException: Type [java.lang.String] is not valid for option items
org.springframework.web.servlet.tags.form.OptionWriter.writeOptions(OptionWriter.java:143)
org.springframework.web.servlet.tags.form.OptionsTag.writeTagContent(OptionsTag.java:157)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
It is just a Spring MVC Web application where i am trying to display the drow down list pre-populated with the colors data.
Any help is highly appreciated.
I added the below line on teh top of addDetails.jsp file and it worked:-
Try to add into Map, instead of ArrayList.
Map<String,String> coloursList = new HashMap<String,String>();
coloursList.put("R","red");
coloursList.put("R","green");
coloursList.put("Y","yellow");
coloursList.put("P","pink");

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.

how to display the names in a jsp page according to name

i have a page editpatient.jsp which includes a page patientlist.jsp. when you run editpatient.jsp then it displays all the records present in the database.I have a dropdown and also a search field to specify searches. So when i run editpatient.jsp then it displays all the records in the manner it is stored in DB. So i wanted to sort it according to name and display.So please tell me how to do the same. when you hit the name or email or city then it will sort accordingly
patientlist.jsp
<%# page import="java.util.*" %>
<%# page import="java.sql.*" %>
<%# page import="DB.*" %>
<%# 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>
<style type="text/css">
.evenRow{
height: 50px;
background-color: white;
text-transform: none;
text-shadow: none;
color: black;
}
.evenRow:hover
{
background-color: #C2FEF0;
}
.row{
height: 50px;
background-color: #E4E6E6;
text-transform: none;
text-shadow: none;
color: black;
}
.row:hover {
background-color: #C2FEF0;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<table style="border-collapse: collapse;overflow-x: scroll; width:97%">
<tr style="background-color:grey;height:50px">
<th style="min-width: 100px">
NAME
</th>
<th style="min-width: 100px">
CITY
</th>
<th style="min-width: 100px">
LAST VISIT
</th>
<th style="min-width: 100px">
MOBILE
</th>
<th style="min-width: 100px">
EMAIL
</th>
<th style="min-width: 100px">
STATUS
</th>
<th style="min-width: 100px">
VIEW
</th>
<th style="min-width: 100px">
EDIT
</th>
</tr>
<%
DataBaseConnection db = new DataBaseConnection();
Connection con = db.connet();
PreparedStatement pt = con
.prepareStatement("select * from Patient");
ResultSet rs = pt.executeQuery();
String searchBy = request.getParameter("searchBy");
String searchElement = request.getParameter("searchElement");
int count = 0;
int index = -1;
boolean name = false;
if ("city".equalsIgnoreCase(searchBy))
index = 9;//change the index to the index of the city
else if ("firstName".equalsIgnoreCase(searchBy))
index = 1;
else if ("lastName".equalsIgnoreCase(searchBy))
index = 2;
else if ("name".equalsIgnoreCase(searchBy)) {
index = 1;
name = true;
}
while (rs.next()) {
if (searchElement == null
|| ((searchElement.equals(rs.getString(index)) && !name) || (name && searchElement
.equalsIgnoreCase(rs.getString(index) + " "
+ rs.getString(index + 1))))) {
if (count++ % 2 == 0) {
%>
<tr class="evenRow" >
<td>
<%=rs.getString(1)%>
</td>
<td>
<%=rs.getString(2)%>
</td>
<td>
<%=rs.getString(3)%>
</td>
<td>
<%=rs.getString(4)%>
</td>
<td>
<%=rs.getString(5)%>
</td>
<td>
<%=rs.getString(6)%>
</td>
<td>
<form action="getPatientDetails.jsp"><input type="hidden" name="hidden" value="<%=count%>"/><input type="submit" value="view"></form>
</td>
<td>
<a onclick="renderEdit(<%out.println("edit");%>)"><%
out.println("edit");
%></a>
</td>
</tr>
<%
} else {
%>
<tr class="row">
<td>
<%=rs.getString(1)%>
</td>
<td>
<%=rs.getString(2)%>
</td>
<td>
<%=rs.getString(3)%>
</td>
<td>
<%=rs.getString(4)%>
</td>
<td>
<%=rs.getString(5)%>
</td>
<td>
<%=rs.getString(6)%>
</td>
<td>
<a onclick="renderView(<%out.println("view");%>)"><%
out.println("view");
%></a>
</td>
<td>
<a onclick="renderEdit(<%out.println("edit");%>)"><%
out.println("edit");
%></a>
</td>
</tr>
<%
}
}
}
%>
</table>
</body>
</html>
editpatient.jsp
<%# page import="java.util.*" %>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
<script type="text/javascript">
var request;
function getRequestObject()
{
if (window.ActiveXObject)
{
return(new ActiveXObject("Microsoft.XMLHTTP"));
}
else if (window.XMLHttpRequest)
{
return(new XMLHttpRequest());
}
else {
return(null);
}
}
function sendRequest()
{
request = getRequestObject();
request.onreadystatechange = handleResponse;
var address = "patientList.jsp?searchBy=" + document.getElementById("searchBy").value + "&searchElement="+ document.getElementById("searchElement").value;
request.open("GET", address, true);
request.send(null);
}
function handleResponse()
{
if (request.readyState == 4 && request.status == 200)
{
document.getElementById("table").innerHTML = request.responseText;
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Edit Patient</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<form id="f1" name="f1" method="post" onsubmit="ccheck();" >
<script>
$(document).ready(function() {
$("#datepicker").datepicker();
});
</script>
<section id="page" > <!-- Defining the #page section with the section tag -->
<header > <!-- Defining the header section of the page with the appropriate tag -->
<hgroup align="center">
<h3>Edit Patient</h3>
</hgroup>
</header>
<section id="articles"> <!-- A new section with the articles -->
<!-- Article 1 start -->
<div class="line"></div> <!-- Dividing line -->
<article id="article1"> <!-- The new article tag. The id is supplied so it can be scrolled into view. -->
<div class="articleBody clear">
search:
<select id="searchBy">
<option value="lastName">Last Name</option>
<option value="firstName">First Name</option>
<option value="name">Name</option>
<option value="city">City</option>
</select>
<input id="searchElement"/>
<input type="button" value="Search" onclick="sendRequest();"/>
</div>
</article>
<div id="table" align="center">
<jsp:include page="patientList.jsp" />
</div>
</article>
</section>
<footer> <!-- Marking the footer section -->
<div class="line"></div>
Go UP
</footer>
</section> <!-- Closing the #page section -->
<!-- JavaScript Includes -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="jquery.scrollTo-1.4.2/jquery.scrollTo-min.js"></script>
<script src="script.js"></script>
</form>
</body>
</html>
See if this links help you.
http://tympanus.net/codrops/2009/10/03/33-javascript-solutions-for-sorting-tables/
http://www.allmyscripts.com/Table_Sort/
Also let us know if you tried anything already
1.First store the dropdown /search value in Model class(using setter).
2.When you fired a query to fetch the details from database append the dropdown /search value which is stored in model class(using getter).
3.After fetch the value from DB render the dataTable .
Suggestion :
Please Follow the any one MVC architecture (Like Spring MVC architecture) to avoid the complexity of the your project.
Thanks you.
ASFAIK, The solution to your problem is ,you can use the jquery in jsp code, So you can find all Library's and include in it . There is no need to worry about sort and editing . Jquery has the Data Tables which has inbuilt API to sort the data in listed tables, its possible to edit the data in the table.
Reference Edit Reference Sort How to use data table in jsp pages
This is not exactly answers to question.
Try grid like jqGrid which takes care of things like sorting, searching, etc..

Ajax with Spring MVC not working

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.

Categories