I am using Spring MVC and I have an AJAX which is used to delete selected user. It's working fine on my local system but when I tried to run the same code on development server I'm getting
500 Internal Server Error
I did google to figure out what is wrong with my code but I'm not able to figure out anything till now. Any help will be appreciated.
AJAX function in my JSP file:
$('.del-btn .userId').click(function(){
var userId = $(this).attr("alt");
var data = 'userId='+ userId;
$.ajax({
type: 'POST',
url: '${pageContext.servletContext.contextPath}/deleteUser',
data: data,
success: function(response) {
$('#submitkpi').submit();
}
});
});
deleteUser function in Controller:
#RequestMapping(value = "/deleteUser", method = RequestMethod.POST)
public #ResponseBody Map<String, ? extends Object> deleteKpi(#ModelAttribute(value = "userId") String userId, BindingResult result) {
if (!userId.isEmpty()) {
userService.deleteUser(userId);
return Collections.singletonMap("ok", true);
}
return Collections.singletonMap("errorMsg", "Unable to complete your request!");
}
Can you try this?!
$('.del-btn .userId').click(function(){
var userId = $(this).attr("alt");
$.ajax({
url: 'deleteUser',
data: ({
userId : userId,
}),
success: function(response) {
alert(response)
}
});
});
Controller
#RequestMapping("/deleteUser")
#ResponseBody
public String deleteKpi(#RequestParam(value = "userId") Long userId, HttpSession session) {
if (null != userId) {
userService.deleteUser(userId);
return "Ok";
}
return "NotOk";
}
Related
I'm new to spring boot framework.
I have a jQuery method that gets called upon the click of a span element. In that jQuery method, I have an ajax call which makes a call to the spring boot controller and passes a string as a parameter. The controller is getting the parameter passed from the ajax call. But it is not redirecting to a different view. The different view is an html page called ajaxView.html. I want to add an attribute to the view as well. Any help would be great.
Here's my ajax call:
$(document).ready(function() {
$('.spanClass').on('click', '#id_1', function(event){
event.stopPropagation();
var str = ((event.target.parentElement).parentElement.href);
$.ajax({
type: 'POST',
url: "http://localhost:8080//span/view?term="+encodeURIComponent(str),
contentType: 'text/plain',
crossDomain: false,
async:true,
success:function(response) {
}
});
});
});
Here's my controller method:
#RequestMapping(method=RequestMethod.POST, value = "/span/view")
public #ResponseBody ModelAndView redirectAjax(String term, Model model) {
Employee emp = new Employee();
emp.setName(term);
model.addAttribute("employee", emp);
return new ModelAndView("redirect:/ajaxView");
}
you need to call a controller again form your Ajax success function to open the ajaxView.html page for you. :--
1.) your ajax Call should be like this :--
$.ajax({
type: 'POST',
url: "http://localhost:8080//span/view?term="+encodeURIComponent(str),
contentType: 'text/plain',
crossDomain: false,
async:true,
success:function(response) {
window.location = '/yourAjaxControllerName';
}
});
2.) Your controller :--
#RequestMapping("/yourAjaxControllerName")
public String getAjaxViewPage(HttpServletRequest request,Model model) {
return "ajaxView";
}
You need to do this in Ajax itself.
In success method of Ajax call you need to resent the response.
$(document).ready(function() {
$('.spanClass').on('click', '#id_1', function(event){
event.stopPropagation();
var str = ((event.target.parentElement).parentElement.href);
$.ajax({
type: 'POST',
url: "http://localhost:8080//span/view?term="+encodeURIComponent(str),
contentType: 'text/plain',
crossDomain: false,
async:true,
success:function(emp) {
alert(emp);
window.location.href = '/JspControllerHandler?employee='+ JSON.stringify(emp); // redirect //this would be GET
}
});
});
});
Your controller will return Employee data to requesting Ajax.
#RequestMapping(method=RequestMethod.POST, value = "/span/view")
public #ResponseBody Employee redirectAjax(String term, Model model) {
Employee emp = new Employee();
emp.setName(term);
return emp;
}
You Ajax will have responsibly to redirect to another page
#RequestMapping("/JspControllerHandler")
public String redirectJsp(HttpServletRequest request,#RequestParam("employee") String empStr) {
Employee employee = null;
try
{
ObjectMapper mapper = new ObjectMapper();
employee = mapper.readValue(empStr, Employee.class);
model.addAttribute("employee", employee );
}
catch(Exception ex)
{
System.out.println("Error while converting JSON string to employee object.");
ex.printStackTrace();
}
return "jspView";
}
I am new to Spring MVC and I am trying to send my data to Spring-MVC Controller using AJAX, on button click. I have written this code (given below) but I am getting error instead of success. please tell what can be the issue?
AJAX:
function add() {
var name = $('#name').val();
$.ajax({
url : "/addUser",
data : name,
type : "POST",
async: false,
success : function(response) {
alert( response );
},
error : function() {
alert("error....");
}
});
}
JAVA
#RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(#ModelAttribute("UserTest") String name) {
//task
return name;
}
I have a spring project and i am calling my controller from ajax call and i want to return arraylist of an object. In debug it shows proper contents in java code.But in js it gives error. Internal server error 500 .
Here is my controller
#RequestMapping(value = "/viewValidationFailures", method = RequestMethod.GET)
public #ResponseBody ArrayList<ErrorTable> viewValidationFailures(
HttpSession session, Principal principal) {
// System.out.println("parameter"+parameter);
ArrayList<ErrorTable> errorTables = null;
SystemUser systemUser = logincontrollerserviceint.getUserByUsername(principal.getName());
errorTables = validationErrorControllerInterface.getValidationErrorsByUser(systemUser);
return errorTables;
}
This is my angular js ajax call
var helloApp = angular.module("helloApp", []);
helloApp.controller("HttpController", [ '$scope', '$http',
function($scope, $http) {
debugger;
$http({
method : 'GET',
url : 'http://localhost:8080/sms/client/viewValidationFailures',
}).success(function(data, status, headers, config) {
debugger;
$scope.errors = data;
$scope.curPage = 0;
$scope.pageSize = 10;
$scope.numberOfPages = function() {
return Math.ceil($scope.errors.length / $scope.pageSize);
};
$('#LoadingImageDiv').hide();
}).error(function(data, status, headers, config) {
debugger;
$('#LoadingImageDiv').hide();
});
} ])
This is my ErrorTable class
#Column(name = "\"eSTId\"")
private String eSTId;
#Column(name = "\"errorCode\"")
private String errorCode;
#Column(name = "\"errorDescription\"")
private String errorDescription;
#Column(name = "\"timeDate\"")
private String time;
Everytime during ajax call it goes into the error function.
Can somebody suggest me what's wrong here.
I have checked all similar links like
Ajax call results in 500 Internal Server Error
Ajax call Gives internal server error
but nothing worked for me.
I ma using Spring MVC and trying to use jQuery. I have this on my web page:
$(document).ready(function () {
var entity = {mag: "status_key", paper: "View10"};
$("#btn").click(function () {
$.ajax({
url: "ajaxJsonPost",
type: 'post',
dataType: 'json',
data: JSON.stringify(entity),
contentType: 'application/json',
});
});
});
Spring server has this:
#RequestMapping(value = "ajaxJsonPost", method = RequestMethod.POST)
public void postJson(#RequestBody Entity en) throws IOException {
System.out.println("writing entity: " + en.toString());
}
OK, Entity cames to server. BUT browser console prints 404 not found. I know that my POST request needs any response. In the Internet I've found solution which recommends me to return ResponseEntity object, OR use annotation #ResponseStatus. They both return HttpStatus well, but I don't know in which cases I should use them. What is the best way?
#Controller
#RequestMapping("/apipath")
public class SomeController {
#RequestMapping(value = "/ajaxJsonPost", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public String postJson(#RequestBody final Entity en) {
System.out.println(en.toString());
//assuming you have a class "EntityService" and
//it has a method postData
//which takes Entity object as parameter and pushes into database.
EntityService.postData(en);
System.out.println("added");
return "success";
}
}
Entity object on the Server side
#JsonAutoDetect
public class Entity {
private String mag;
private String paper;
public String getMag() {
return mag;
}
public void setMag(final String mag) {
this.mag = mag;
}
public String getPaper() {
return paper;
}
public void setPaper(final String paper)
this.paper = paper;
}
}
ajax
$(document).ready(function () {
var entity = {mag: "status_key", paper: "View10"};
$("#btn").click(function () {
$.ajax({
url: "/apipath/ajaxJsonPost",
type: 'post',
dataType: 'json',
data: JSON.stringify(entity),
contentType: 'application/json',
success : function(response) {
alert(response);
},
error : function() {
alert('error');
}
});
});
});
And as far as why and when to use #ResponseStatus and #ResponseEntity, there is already a short and simple answer here by #Sotirios Delimanolis. When use #ResponseEntity .
It says :
ResponseEntity is meant to represent the entire HTTP response. You can
control anything that goes into it: status code, headers, and body.
#ResponseBody is a marker for the HTTP response body and
#ResponseStatus declares the status code of the HTTP response.
#ResponseStatus isn't very flexible. It marks the entire method so you
have to be sure that your handler method will always behave the same
way. And you still can't set the headers. You'd need the
HttpServletResponse or a HttpHeaders parameter.
Basically, ResponseEntity lets you do more.
My web application is basen on Spring MVC (4.0.5).
I'm trying to send a POST request through AJAX, using jQuery (v. 2.1.1):
function deleteItem(id) {
alert("Deleting " + id);
$.ajax({
url: "ajax/delete_item",
type: 'POST',
dataType: 'html',
data: {"id": id},
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
var txt = data;
$('#message').html(txt);
},
error: function(data, status, err) {
$('#message').html(err);
}
});
}
The Controller's method is called successfully but there are no parameters in the request:
#RequestMapping(value = "/ajax/delete_item", method = RequestMethod.POST)
public #ResponseBody String ajaxDelete(HttpServletRequest request) {
Enumeration<String> en = request.getParameterNames();
while (en.hasMoreElements()) {
String pname = en.nextElement();
System.out.println("//// " + pname); // just for test
}
String idStr = request.getParameter("id");
Integer id = Integer.parseInt(idStr);
//...
Why the request parameter is lost? Not just the value, the parameter itself is also lost.
What's wrong here?
If you are passing content type contentType: 'application/json' from ajax then add that settings in Spring method declaration as below: ( add produces = "application/json" in definition)
#RequestMapping(value = "/ajax/delete_item", method = RequestMethod.POST , produces = "application/json")
public #ResponseBody String ajaxDelete(HttpServletRequest request) {
also there's one more caveat that,
You are mentioning both datatype and mimeType but it is not uniform.
mimeType: 'application/json' should be written with dataType: 'json' and not html.
I am not 100% sure what is wrong with your solution but I can give you an example that works for me
The AJAX request using Jquery :
// Do AJAX
$(function () {
$.post(mobileUrl + "/leave/requestLeave",
{ startDate: startDate, endDate: endDate, leaveTypeId: leaveTypeId,
notes: notes, isStartDayHalfDay: isStartDayHalfDay, isHalfDayEndDay: isHalfDayEndDay },
function (response) {
$('#feedbackTextArea').show();
}
);
});
And the controller method
#RequestMapping(value = "/requestLeave", method = RequestMethod.POST)
#ResponseBody
public String createOrUpdateNewForm(String startDate, String endDate, String leaveTypeText, String leaveTypeId,
String notes, String isStartDayHalfDay, String isHalfDayEndDay) {
startDate = new DateTime(startDate).toDate() etc
}
}
One thing to remember is that the parameter names in the ajax request should match the names of the variables in the controller method implementation
$("#drpop").change(function () {
var code = $(this).val();
$.ajax({
url: '/Ordering/OrderingTable',
type: 'post',
datatype: 'json',
data: { OperCode: code },
success:function(msg){
alert(msg);
} }); });
[HttpPost]
public ActionResult OrderingTable(string OperCode)
{
Orderingbll order = new Orderingbll();
var result = order.ListCategory(OperCode);//here you write your code
return Json(result,JsonRequestBehavior.AllowGet);
}