Reputation: 771
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>
<a href="/SpringMVC/search">Show All Users</a>
</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?
Upvotes: 2
Views: 3659
Reputation: 1249
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.
Upvotes: 4
Reputation: 624
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.
Upvotes: 2
Reputation: 48837
Try
data: {firstName: firstName, lastName: lastName},
instead of
data: "firstName=" + firstName + "&lastName=" + lastName,
in your ajax call.
Upvotes: 4
Reputation: 27604
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' />",
Upvotes: 6