Send a data through Ajax, and the background never receives it - java

The foreground sends an ID to the background through Ajax, but the background never receives it. I have been troubled by this problem for a whole day, and I really need your help.Here are my JS and Controller and error messages
$('.category-wrap').on('click', '.now .delete', function (e) {
var target = e.currentTarget;
var pc = target.dataset.id;
var pcId = {'pcId':pc};
$.confirm('sure?',function () {
$.ajax({
url: deleteUrl,
type: 'POST',
data: pcId,
contentType: 'application/json',
cache: false,
success: function (data) {
if (data.success) {
$.toast('successfully delete!');
getList();
} else {
$.toast('Delete failed!');
}
}
});
})
});
#RequestMapping(value = "/removeproductcategory", method = RequestMethod.POST)
#ResponseBody
public Map<String, Object> removeProductCategory(#RequestBody Integer pcId,
HttpServletRequest request)
{...}
image 1
image 2

you send a json request var pcId = {'pcId':pc}; and try to receive an Integer #RequestBody Integer pcId
try to define a Pojo like this
class RequestData {
public Integer pcId;
}
and modifiy controller method parameter
#RequestMapping(value = "/removeproductcategory", method = RequestMethod.POST, consumes = "application/json" )
#ResponseBody
public Map<String, Object> removeProductCategory(#RequestBody RequestData pcId,
HttpServletRequest request)

Related

How to convert JSon Object to Java Object?

Can Anyone help me on this, i m trying to convert complex json object send through ajax into a object. so that i can use this object to pass into my model.
The JSP code is:
function callRemovefilter()
{
var jsonObjects = {
address1: "Address_1",
city: "City",
pin: "PIN"
};
var jsonObjects2 = {
locality:"Loc1",
shippingType:"Regular",
shippingCost:20
};
var cust= JSON.stringify(jsonObjects);
var sales=JSON.stringify(jsonObjects2);
jQuery.ajax({
url: "http://localhost:8080/OnlineStore/kmsg/grocery/SaveSalesOrder",
type: "GET",
data: {CustomerInfo:cust,SalesModel:sales},
dataType: "json",
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(result) {
//Write your code here
}
});
}
// The controller code is
#RequestMapping(value = "/SaveSalesOrder", method = RequestMethod.GET)
#ResponseStatus(value=HttpStatus.OK)
public #ResponseBody String SaveCustomerOrder(#RequestParam Map<String,String> requestParams) throws Exception
{
ObjectMapper objectMapper = new ObjectMapper();
SalesCommandObject salesCommandObject= new SalesCommandObject();
salesCommandObject = objectMapper.readValue(body, SalesCommandObject .class);
return "Success";
}
// Code of JSP to send object to controller
var salesCommandObject = {}; salesCommandObject.CustomerInfo =
{
"address1": "Address_1",
"city": "City",
"pin": "PIN"
};
salesCommandObject.SalesModel =
{
"locality":'Loc1',
"shippingType":'Regular',
"shippingCost":20
};
$.ajax
({
type: "POST",
dataType : 'json',
async : true,
url: "http://localhost:8080/OnlineStore/kmsg/grocery/SaveSalesOrder",
data : JSON.stringify(salesCommandObject),
}).done(function(data,type,xml)
{
console.log(data);
}).fail(function()
{
alert("Something Bad Happened, Service failed");
})
Send objects, not jsonstrigs. And in controller in your method SaveCustomerOrder get an object, not Map, like:
#RequestMapping(value = "/SaveSalesOrder", method = RequestMethod.GET)
#ResponseStatus(value=HttpStatus.OK)
public #ResponseBody String SaveCustomerOrder(#RequestParam CustomerInfo ci, #RequestParam SalesModel sm) throws Exception
{
//your logic here
return "Success";
}
And add getters and setters to appropriate classes(i.e CustomerInfo, SalesModel) like:
`public class SalesModel{
private String sale_id;//or whatever field or property you need
public String getSale_Id() {
return sale_id;
}
public void setSale_Id(String si) {
this.sale_id = si;
}
}`

how can I send and retrieve params in spring?

I am triyng to do a simple thing, with ajax, send a request (using a GET, or POST).
I will be sending 2 parameters in a json format , and I just want to get them back and send a response, still, I always get an error 400 and others that I dont know whats wrong, any idea how?
I started based on this article: http://fruzenshtein.com/spring-mvc-ajax-jquery/
I am using spring mvc.
So far I have this:
$(".update_agent").live('click', function(){
var agent = { "agentId" : agentID, "hostAGent" : hostID};
//send ajax
$.ajax({
url: url,
data: JSON.stringify(agent),
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data) {
alert("success");
},
error: function(){
alert("error");
}
});
})
and at my java controller I have this
#RequestMapping(value = "/update", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public int updateAgent(HttpServletRequest req, HttpServletResponse res) throws IOException{
req.getParameterValues("agentId");
return AGENT_UPDATE_SUCCESS;
}
But I cant get it back, have no idea how to make the request of the params, any idea?
Thanks.
=====================UPDATE============================
Ive changed the code and this how it looks like...
$.ajax({
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
type: 'POST',
url: url,
data: JSON.stringify(agent),
dataType: 'json',
success:function(data) {
alert("success");
},
error: function(){
alert("error");
}
});
And at my controller
#RequestMapping(value = "/update", method = RequestMethod.POST)
public #ResponseBody Integer updateAgent(#RequestBody String param) throws IOException{
System.out.println(param);
//do something...
return 1;
}
the problem is that I am getting an error 415, unsupported media type, any advice?
GET-request can not have 'data'-field. You need to send your data as part of the url:
$.ajax({
url: url + "?agent=" + JSON.stringify(agent),
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data) {
alert("success");
},
error: function(){
alert("error");
}
});
now you can get the data in your controller as:
#ResponseBody public ResponseEntity<String> updateAgent(#RequestParam(value = "agent") String agentJson){
...
}
or you can send a POST-request. With a POST-request you can send your data as requestBody:
public #ResponseBody ResponseEntity<String> updateAgent(#RequestBody String agentJson){
...
}
EDIT:
create a new Agent-class:
public class Agent {
private long agentId;
private long hostAgent;
...
getter and setter
...
}
now update the controller to:
public #ResponseBody ResponseEntity<String> updateAgent(#RequestBody Agent agent){
System.out.println(agent.getAgentId());
}
and change the "Content-Type" of ajax-call to "application/json".
EDIT2:
change your ajax-call data to:
data: { agentId: agentID, hostAgent : hostAgentID} ,
or even
data: agent ,
Don't forget to change "hostAGent" to "hostAgent" in your agent object, or you will get 400!!!
now ajax will send the data as request parameters, you can get the data in your controller by:
public #ResponseBody ResponseEntity<String> updateAgent(#RequestParam(value = "agentId") long agentId, #RequestParam(value = "hostAgent") long hostAgentId){
System.out.println(agentId);
}

I got 404 error after sending POST method from ajax (#ResponseStatus & ResponseEntity)

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.

JQuery, AJAX, POST request, parameters lost

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);
}

Redirect to another controller after ajax call

I want to redirect to another controller after a successful ajax call also i want to send some data that I get in the response
User Controller
#RequestMapping(method = RequestMethod.POST, value = "/user/preferences")
public #ResponseBody Map<String, List<String>> userPreferences(HttpServletRequest request) {
Map<String , List<String>> finalPlaces = new LinkedHashMap<String, List<String>>();
finalPlaces.put(entry.getKey(), new ArrayList<String>(topPlaces));
return finalPlaces;
}
Ajax Call
$(".savebutton").click(function(){
$.ajax({
url: "<c:url value='/user/preferences' />",
type: 'POST',
data:{
preferences : preferences
},
success: function(response)
{
},
error: function(xhr, ajaxOptions, thrownError) {
alert('Error');
}
});
});
when the above ajax call returns successfully I want to call a method of another controller
Places Controller
#RequestMapping(method = RequestMethod.GET, value = "/places")
public ModelAndView showRecommnededPlaces(Map<String, List<String>> recommndedPlaces) {
System.out.print(recommndedPlaces);
ModelAndView model = new ModelAndView("places");
return model;
}
is it possible to directly call the places controller action from the user controller?
Thanks
Yes, you can return "redirect:/places"; in your user controller, like:
#RequestMapping(method = RequestMethod.POST, value = "/user/preferences")
public #ResponseBody String userPreferences(HttpServletRequest request) {
Map< String, Integer> userPreferences = new HashMap< String, Integer>();
.
.
.
return "redirect:/places";
}
If you are okay about putting dependency from one controller to the next, you can actually do this:
public class UserController {
#Autowired PreferencesController prefController;
#RequestMapping(method = RequestMethod.POST, value = "/user/preferences")
public #ResponseBody Map<String, List<String>> userPreferences(HttpServletRequest request) {
Map<String , List<String>> finalPlaces = new LinkedHashMap<String, List<String>>();
finalPlaces.put(entry.getKey(), new ArrayList<String>(topPlaces));
return prefController. showRecommendedPlaces(finalPlaces);
}
}
Not saying this is good - since you will have to match the response type of your called controller appropriately, but nevertheless an approach

Categories