How to send Long and Double through Ajax to Spring controller? - ajax

I want to send Long and Double to Spring controller use Ajax.
var id = $(this).data('customer-id');
var quantity = $('#quantity-' + id).val();
$.ajax({
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
type: "POST",
url: '/changeQuantityOrder',
data: {idOrder: id, quantityChange: quantity},
error: function(e) {
console.log(e);
},
success: function (msg) {
window.location.href = "/administrationNotSleeps";
}
I try to receive a code so:
#RequestMapping(value = "/changeQuantityOrder", method = {RequestMethod.POST})
public #ResponseBody Long editCustomerOrder(#RequestParam(value = "idOrder")Long id,
#RequestParam(value = "quantityChange")Double quantity){
System.out.println("Id:"+id+" Quantity "+quantity );
return id;
}
But I receive exception
{"timestamp":1490775639761,"status":400,"error":"Bad Request","exception":"org.springframework.web.bind.MissingServletRequestParameterException","message":"Required Long parameter 'idOrder' is not present","path":"/changeQuantityOrder"}"
I looked for and have found about this exception (MissingServletRequestParameterException) https://stackoverflow.com/
But this article was written 3 years ago, maybe something changed?
Because now I send String to Spring controller and after that I use split in java.

key should be in quotes
data: {"idOrder": id, "quantityChange": quantity}
Also mention dataType - what kind of response to expect.

Related

ajax MissingServletRequestParameterException: Required request parameter is not present]

I have the error :
MissingServletRequestParameterException: Required request parameter 'employee' for method parameter type Employee is not present]
I don't understand why.
function createEmployee() {
const employee = {};
employee.id = document.getElementById("detailledMatriculeDataLabelId").value;
employee.firstName = document.getElementById("detailledFirstNameDataLabelId").value;
employee.lastName = document.getElementById("detailledLastNameDataLabelId").value;
employee.address = document.getElementById("detailledAddressDataLabelId").value;
employee.title = document.getElementById("detailledTitleDataLabelId").value;
employee.managerId =1;
$.ajax({
url: '/create' ,
data : employee,
type: 'POST ',
success: function(result) {
document.location.reload()
},
error: function() {
console.log ("creation failed ");
}
});
}
'''
#PostMapping(path="/create") // Map ONLY POST Requests
public String createEmployee (#RequestParam Employee employee) {
// #ResponseBody means the returned String is the response, not a view name
// #RequestParam means it is a parameter from the GET or POST request
System.err.println("createEmployee");
employeesRepository .save(employee);
return "/index";
}
'''
I have found many posts, and after many tries got it:
for ajax
data: JSON.stringify(employee),
contentType: "application/json",
and for the java code: replace the #RequestParam with #RequestBody.
AI does not understand why if someone has the answer ...

Put request into Spring Boot Controller

Im trying to send a json string with ajax to my spring boot controller but i keep getting the error net::ERR_TOO_MANY_REDIRECTS, and there are a bunch of $csrfError after the url. I've looked at tons of other websites and questions but I still can't get it to work. how do i correctly setup my ajax request so that my controller will accept the data?
ive already tried changing the method type to post and changing the RequestParams to ResponseBody but i went back to RequestParams
my ajax function
function deleteEvent() {
var startTime = document.getElementById('newStartTime').value;
var endTime = document.getElementById('newEndTime').value;
var type = document.getElementById('newTimeOffType').value;
var search = {startTime: startTime, endTime: endTime, type: type};
if(confirm("Are you sure you want to delete this event?")){
$.ajax({
method: 'PUT',
contentType: 'application/json',
url: '/vacation/deleteEvents',
dataType: 'json',
data: JSON.stringify(search),
success: function () {
console.log('success');
},
error: function (e) {
console.log(e);
}
})
}
else {
alert('you said no')
}
my spring controller
#RequestMapping(value = "/vacation/deleteEvents", method=RequestMethod.PUT)
#ResponseBody
public String deleteCalendarEvents(#RequestParam String startTime, #RequestParam String endTime, #RequestParam String type, HttpSession session ){
User user = (User) session.getAttribute("currentUser");
System.out.println("startTime: " + startTime);
System.out.println("endTime: " + endTime);
System.out.println("type: " + type);
return null;
}
i want it to print out the starttime, endtime, and type into my console but i keep getting this error.

Does Spring Form Backing support takes null as a value of an entity

I have an entity User[userid, name , age]
Now from jsp I am hitting ajax like this:
$.ajax({
type: "POST",
url: "/user/saveUser.htm",
data: "userid=" + userid+ "&name=" + name + "&age=" + age,
success: function (response) {
alert("success");
}
And my controller is:
#ResponseBody
#RequestMapping(value = {"saveUser"}, method = {RequestMethod.POST})
public String submitProblem(HttpServletRequest req, User user)
{
//backend codes
}
My question is when I am sending name="ABC" , age="24" and id=32;
everything is fine.
But "The request sent by the client was syntactically incorrect." response comes if I am sending id=null.
Please help me to know the issue.
try to use json data in your ajax request first you can use
$.ajax({
type: "POST",
url: "/user/saveUser.htm",
data: {'userid': userid, 'name': name, 'age' : age},
success: function (response) {
alert("success");
}
and try to use corectly with spring i cant help you ive never use spring also your error is type of id
if you convert your id on string maybe this will work because your age work try to do
userid = userid.toString();
$.ajax({
type: "POST",
url: "/user/saveUser.htm",
data: "userid=" + userid+ "&name=" + name + "&age=" + age,
success: function (response) {
alert("success");
}

Web Api 2 deserialize LINQ2SQL object with collection property

The context is long, so I'll start with the question: Why isn't the InductionQAs collection property being rehydrated?
In a Web API 2 method, LINQ produces an object ic with a collection property InductionQAs. After I eliminate a huge irrelevant object graph and prevent a circular reference, ic is returned by the method. Here's the code. Error handling has been removed for brevity.
// GET: api/InductionContent/5
[Authorize]
public object Get(int id)
{
var dc = new Models.InductionsDataContext();
var user = GetUser(dc);
var ic = dc.InductionContents.Single(c => c.InductionContentID == id);
ic.User.InductionContents.Clear(); //don't ship this it can be huge
return ic;
}
Here's the invoking JS code. Ignore the authorisation header business, that all works fine.
var token, headers;
$.ajax({ //get session token
url: "api/token",
headers: { Authorization: "Basic " + btoa("username:password") },
}).done(function (result) {
localStorage.setItem('access_token', token = result.access_token);
var headers = { Authorization: "Session " + token };
$.ajax({ //get an induction content object
url: "api/InductionContent/5",
headers: headers
}).done(function (ic) {
//at this point we have an object graph
var json = JSON.stringify(ic);
});
});
This is what JSON.stringify(ic) returns:
{
"InductionContentID": 5,
"InductionTemplateID": 1,
"InductionContent1": "<p>We recognise that it is ...(redacted)</p>",
"InductionContentOrder": 301,
"Caption": "Workplace Health and Safety",
"OwnerId": 0,
"ParentId": 0,
"TopicId": 5,
"InductionQAs": [
{
"InductionQAID": 1,
"InductionContentID": 5,
"Question": "Who is responsible for ...(redacted)",
"Answers": "A|B|C|*D",
"InductionQAOrder": 1
}
],
"User": null
}
All well and good. Now we round-trip it.
$.ajax({
type: "post",
url: "api/InductionContent",
headers: headers,
data: ic
});
This calls into the following web method:
// POST: api/InductionContent
[Authorize]
public void Post([FromBody]Models.InductionContent ic)
{
//redacted
}
The method is invoked and ic has a value. ic.User contains data, but inspection of ic.InductionQAs reveals that it has not been initialised.
Serialisation is configured as follows:
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.MessageHandlers
.Add(new AuthenticationHandler(CreateConfiguration()));
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
MVC is smart but not quite smart enough. It needs a hint. The "round-trip" call should have looked like this:
$.ajax({
type: "post",
url: "api/InductionContent",
contentType: "text/json",
headers: headers,
data: JSON.stringify(ic)
}).done(function (result) {
//etc
});
There are two things to note here.
We have assumed manual control of payload encoding
We have annotated the post with the encoding used
One another thing...
Having got it all to work I decided the method should return the id of the freshly minted database row. Changing the method return type to int and appending a last line
return nc.InductionContentId;
should have been enough, but the done method of the ajax call totally failed to fire. Investigation with Fiddler revealed that the id value had indeed been returned with a content-type of text/json.
When you specify a content type for a jQuery ajax call, the same content type is used for the response. If the return value is an object, this will work fine. The object will be serialised as JSON and at the other end it will be parsed to provide the result object.
But for a simple value like an int, this comes unglued at the parsing stage. To resolve the problem, a return content type of plain text by using the dataType attribute.
$.ajax({
type: "post",
url: "api/InductionContent",
contentType: "text/json",
dataType: "text",
headers: headers,
data: JSON.stringify(ic)
}).done(function (result) {
var id = result;
//etc
});

How to pass Json object from ajax to spring mvc controller?

I am working on SpringMVC, I am passing data from ajax to controller but i got null value in my controller please check my code below
function searchText()
{
var sendData = {
"pName" : "bhanu",
"lName" :"prasad"
}
$.ajax({
type: "POST",
url: "/gDirecotry/ajax/searchUserProfiles.htm,
async: true,
data:sendData,
success :function(result)
{
}
}
MyControllerCode
RequestMapping(value="/gDirecotry/ajax/searchUserProfiles.htm",method=RequestMethod.POST)
public #ResponseBody String getSearchUserProfiles(HttpServletRequest request)
{
String pName = request.getParameter("pName");
//here I got null value
}
any one help me
Hey enjoy the following code.
Javascript AJAX call
function searchText() {
var search = {
"pName" : "bhanu",
"lName" :"prasad"
}
$.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url: "/gDirecotry/ajax/searchUserProfiles.html",
data: JSON.stringify(search), // Note it is important
success :function(result) {
// do what ever you want with data
}
});
}
Spring controller code
RequestMapping(value="/gDirecotry/ajax/searchUserProfiles.htm",method=RequestMethod.POST)
public #ResponseBody String getSearchUserProfiles(#RequestBody Search search, HttpServletRequest request) {
String pName = search.getPName();
String lName = search.getLName();
// your logic next
}
Following Search class will be as follows
class Search {
private String pName;
private String lName;
// getter and setters for above variables
}
Advantage of this class is that, in future you can add more variables to this class if needed.
Eg. if you want to implement sort functionality.
Use this method if you dont want to make a class you can directly send JSON without Stringifying. Use Default Content Type.
Just Use #RequestParam instead of #RequestBody.
#RequestParam Name must be same as in json.
Ajax Call
function searchText() {
var search = {
"pName" : "bhanu",
"lName" :"prasad"
}
$.ajax({
type: "POST",
/*contentType : 'application/json; charset=utf-8',*/ //use Default contentType
dataType : 'json',
url: "/gDirecotry/ajax/searchUserProfiles.htm",
data: search, // Note it is important without stringifying
success :function(result) {
// do what ever you want with data
}
});
Spring Controller
RequestMapping(value="/gDirecotry/ajax/searchUserProfiles.htm",method=RequestMethod.POST)
public #ResponseBody String getSearchUserProfiles(#RequestParam String pName, #RequestParam String lName) {
String pNameParameter = pName;
String lNameParameter = lName;
// your logic next
}
I hope, You need to include the dataType option,
dataType: "JSON"
And you could get the form data in controller as below,
public #ResponseBody String getSearchUserProfiles(#RequestParam("pName") String pName ,HttpServletRequest request)
{
//here I got null value
}
If you can manage to pass your whole json in one query string parameter then you can use rest template on the server side to generate Object from json, but still its not the optimal approach
u take like this
var name=$("name").val();
var email=$("email").val();
var obj = 'name='+name+'&email'+email;
$.ajax({
url:"simple.form",
type:"GET",
data:obj,
contentType:"application/json",
success:function(response){
alert(response);
},
error:function(error){
alert(error);
}
});
spring Controller
#RequestMapping(value = "simple", method = RequestMethod.GET)
public #ResponseBody String emailcheck(#RequestParam("name") String name, #RequestParam("email") String email, HttpSession session) {
String meaaseg = "success";
return meaaseg;
}

Resources