I made ajax request, but it don't see Post Controller, which need to handle request. But if i change POST to GET - Get Controller handle ajax request.
My Post Controller:
#RestController
public class AddProductController extends AbstractController {
private static final long serialVersionUID = 5023867691534917359L;
private static final Logger LOGGER = LoggerFactory.getLogger(AddProductController.class);
#PostMapping("/ajax/json/product/add")
public ShoppingCart addProductToCart(HttpServletRequest req,
#RequestParam(name = "idProduct") String idProduct,
#RequestParam(name = "count") String count) {
ProductForm productForm = createProductForm(idProduct, count);
ShoppingCart shoppingCart = SessionUtil.getCurrentShoppingCart(req); // Get ShoppingCart
orderService.addProductToShoppingCart(productForm, shoppingCart); // Add product in Cart
return shoppingCart;
}
Ajax request:
var addProductToCart = function (){
var idProduct = $('#addProductPopup').attr('data-id-product');
var count = $('#addProductPopup .count').val();
var btn = $('#addToCart');
convertButtonToLoader(btn, 'btn-primary');
$.ajax({
url : '/ajax/json/product/add',
method : 'POST',
data: {
idProduct : idProduct,
count : count
},
success : function(data) {
$('#currentShoppingCart .total-count').text(data.totalCount);
$('#currentShoppingCart .total-cost').text(data.totalCost);
$('#currentShoppingCart').removeClass('hidden');
convertLoaderToButton(btn, 'btn-primary', addProductToCart);
$('#addProductPopup').modal('hide');
},
error : function(xhr) {
convertLoaderToButton(btn, 'btn-primary', addProductToCart);
if (xhr.status == 400) {
alert(xhr.responseJSON.message);
} else {
alert('Не сработала JS функция добавления в коризну');
}
}
});
};
Whats wrong with my PostController?
Jquery.ajax does not encode POST data for you automatically the way that it does for GET data. Jquery expects your data to be pre-formatted to append to the request body to be sent directly across the wire.
A solution is to use jQuery.param function to build a query string that process POST requests expect.
Change data object in you method to the format below, and hopefully, it will work.
data: jQuery.param({ idProduct : idProduct, count : count }),
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
Change your ajax like below. You do not need to send data because you are not expecting data in body in your post controller.
$.ajax({
url : '/ajax/json/product/add?idProduct='+idProduct+'&count='+count,
method : 'POST',
success : function(data) {
$('#currentShoppingCart .total-count').text(data.totalCount);
$('#currentShoppingCart .total-cost').text(data.totalCost);
$('#currentShoppingCart').removeClass('hidden');
convertLoaderToButton(btn, 'btn-primary', addProductToCart);
$('#addProductPopup').modal('hide');
},
error : function(xhr) {
convertLoaderToButton(btn, 'btn-primary', addProductToCart);
if (xhr.status == 400) {
alert(xhr.responseJSON.message);
} else {
alert('Не сработала JS функция добавления в коризну');
}
}
});
Related
I am new to java, i am trying to pass two json objects from ajax call to controller class... but i am getting below exception
Resolved exception caused by Handler execution: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String com.controllers.EmployeeController.saveData(java.lang.String,com.entities.EmployeeData,org.springframework.validation.BindingResult)
Jquery Code:
$("#saveData").submit(function(event) {
var data = [];
var formData = {};
var myJsonString;
var slab, lower;
$("table tbody tr").each(function(index) {
//alert(index);
slab = $(this).find('.slab').val();
lower = $(this).find('.lower').val();
if(slab != undefined && lower != undefined){
var form1 =new Object();
form1.slab=slab;
form1.lower=lower;
data.push(form1);
}
});
var form = this;
event.preventDefault();
$.each(this, function(i, v){
var input = $(v);
formData[input.attr("name")] = input.val();
});
var url = "/Portal/SaveData";
ajaxCall(url,formData,data);
});
function ajaxCall(url,formData,data){
//alert("AjaxPost!!!"+url);
// DO POST
$.ajax({
type : "POST",
contentType : "application/json",
url : url,
data : JSON.stringify({formData:formData,value:data}),
dataType : 'json',
beforeSend: beforeSendHandler,
success : function(response) {
alert("Success");
}else{
alert("else");
}
},
error : function(e) {
bootbox.alert({
size: "small",
title: "ALERT",
message: "There seems to be some problem while Proccessing record!"
})
}
});
}
Controller Method:
#RequestMapping(value = "/SaveData", method = RequestMethod.POST)
public #ResponseBody String saveData(#RequestBody String value,#Valid #RequestBody EmployeeData emp, BindingResult result) {
System.out.println(" Creating!!!");
//logic here
}
Where is the mistake in ajax call or in controller file?
there is any other way to pass multiple json objects to controller class file?
The #RequestBody annotation is expected to map to one and only one parameter in your method and to contain the entire contents of the incoming request.
You should map all your form data into a single JSON object, then handle that as a single JSON object in the backend as well.
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;
}
Can u explain me why DELETE method (store.remove() in Edit.js) throws 400 Bad request. Other method works well. In header request url seems to be ok "http://localhost:8080/Diary/rest/notes/22?_dc=1461837327580".
I know that problem is in payload of DELETE method, store.remove() includes ID as payload. How can i disable that and send DELETE method without body, because ID is already in URL
Rest Service
#Path("/notes")
public class NoteRestService {
#Context
private UriInfo uriInfo;
#Context
private HttpServletRequest request;
private NoteDaoImpl noteDao = new NoteDaoImpl();
#GET
#Produces("application/json")
public String getNotes(){
String login = request.getSession(true).getAttribute("login").toString();
List<Note> notes = noteDao.getUserNotes(login);
return new Gson().toJson(notes);
}
#POST
#Consumes("application/json")
public Response postNote(Note note){
String login = request.getSession(true).getAttribute("login").toString();
note.setUser(login);
noteDao.persist(note);
URI noteUri = uriInfo.getAbsolutePathBuilder().path(Long.toString(note.getId())).build();
return Response.created(noteUri).build();
}
#PUT
#Path("{id}")
#Consumes("application/json")
public Response updateNote(#PathParam("id") String id,Note note){
String login = request.getSession(true).getAttribute("login").toString();
Note editNote = noteDao.getNote(Long.parseLong(id));
note.setCreated(editNote.getCreated());
note.setUser(login);
noteDao.update(note);
return Response.ok().build();
}
#DELETE
#Path("{id}")
public Response deleteNote(#PathParam("id") String id){
Note note = noteDao.getNote(Long.valueOf(id));
if (note==null){
throw new NotFoundException();
}
noteDao.delete(Long.parseLong(id));
return Response.noContent().build();
}
}
EditController.js
Ext.define('MVC.controller.Edit', {
extend: 'Ext.app.Controller',
init: function () {
this.control({
'editForm > button#SaveRecord': {
click: this.onSaveButtonClick
},
'editForm > button#DeleteButton': {
click: this.onDeleteButtonClick
}
});
},
onSaveButtonClick: function (btn) {
//get reference to the form
var detailView = btn.up('editForm');
//get the form inputs
var data = detailView.getValues();
//see if the record exists
var store = Ext.getStore('TestStore');
console.log(data.id);
var record = store.getById(data.id);
if (!record) {
record = Ext.create('MVC.model.Note', {
title: data.title,
created: new Date(),
updated: new Date(),
text: data.text
});
Ext.MessageBox.alert('Created', data.title);
store.insert(0, record);
store.sync();
return;
}
record.set(data);
store.sync();
//manually update the record
detailView.updateRecord();
},
onDeleteButtonClick: function (btn) {
//get reference to the form
var detailView = btn.up('editForm');
//get the form inputs
var data = detailView.getValues();
var store = Ext.getStore('TestStore');
var record = store.getById(data.id);
store.remove(record);
store.sync();
}
});
UPD: Store
Ext.define('MVC.store.TestStore', {
extend: 'Ext.data.Store',
requires: [
'MVC.model.Note'
],
storeId: 'TestStore',
model: 'MVC.model.Note',
autoLoad: false,
proxy: {
type: 'rest',
url: 'rest/notes',
actionMethods: {
create: 'POST',
read: 'GET',
update: 'PUT',
destroy:' DELETE'
},
reader: {
type: 'json',
rootProperty: 'data'
},
writer: {
type: 'json',
writeAllFields: true
}
}
});
You can't have a HttpMethod.DELETE with a body.
This is not explicitly stated in the RFC, but some Proxy servers will reject the body if you have one in a delete method. Spring lowers the standard and will reject your query with a Bad Request.
Remove the body as well as the answer to fix your issue.
Check this for more information:
Is an entity body allowed for an HTTP DELETE request?
If TestStore is the store you're using, I'd guess that your problem is here:
actionMethods: {
create: 'POST',
read: 'GET',
update: 'PUT',
destroy: 'GET'
},
I don't recognize the #DELETE annotation, so I'm not 100% sure but if your controller is expecting DELETE, and you're sending GET, that could explain the 400 error.
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);
}