Spring MVC + Ajax error 400 - json

I have a simple java application on Spring MVC and I send ajax request to Spring controller. When I set headers "Accept", "application/json" and "Content-Type", "application/json;charset=utf-8" in AJAX call I get error 400 in dubugger, when I delete it I get error 415.
If I change controller method signature to public String logoutPage (#RequestBody String obyavleniye) I get JSON string. What problem can be with parse request in controller?
JS method:
$("#advertForm").submit(function(e) {
e.preventDefault();
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
var obyavleniye = {
title: "Title",
price: "80",
description: "desc",
date: "2016-11-07 18:30:21",
authorid: "2",
category: "A",
state: "new",
img1: "http",
img2: "http",
img3: "http",
img4: "http",
};
var post_data = JSON.stringify(obyavleniye);
console.log(post_data);
$.ajax({
url : "/upload",
type: "POST",
dataType: 'json',
data: post_data,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8");
xhr.setRequestHeader(header, token);
},
complete: function() {
console.log("Sent");
},
success: function (response) {
console.log("success");
console.log("response" + response);
},
error: function (data) {
console.log("error");
console.log(data);
}
});
});
Controller method:
#ResponseBody
#RequestMapping(value="/upload", method = RequestMethod.POST)
public String logoutPage (#RequestBody Advert obyavleniye) {
// public String logoutPage (#RequestBody String obyavleniye) {
System.out.println("Enter: " + obyavleniye);
this.advertService.addAdvert(obyavleniye);
// return "{\"msg\":\"success\"}";
return "{\"title\":\"Title\",\"price\":\"80\",\"description\":\"normm\",\"date\":\"2016-11-07 18:30:21\",\"authorid\":\"2\",\"category\":\"A\",\"state\":\"new\",\"img1\":\"http\",\"img2\":\"http\",\"img3\":\"http\",\"img4\":\"http\"}";
}

My sample code.
js
Company.prototype.saveCompanyLocation = function() {
/* company */
var companyIdx = $('#companyIdx').val();
var locationIdx = $('#locationIdx').val();
var data = {
idx : locationIdx,
postCode : $('#postCode').val(),
address : $('#address').val(),
detailAddress : $('#detailAddress').val(),
tel : $('#tel').val(),
fax : $('#fax').val(),
email : $('#email').val(),
language : $("#language").val(),
latitude : $('#latitude').val(),
longtitude : $('#longtitude').val()
};
data = JSON.stringify(data);
$.ajax({
url : "/gpim/company/settings/location/save/" + companyIdx,
type : 'POST',
data : data,
contentType : 'application/json',
success : function(response) {
if (response == "success") {
document.location.reload(true);
} else {
$("#editMsg").text("you can`t save location information.");
}
},
error : function(request, status, error) {
}
});
};
controller
#RequestMapping(value = "/settings/location/save/{companyIdx}", method = RequestMethod.POST)
public #ResponseBody String saveLocation(#PathVariable int companyIdx, #RequestBody CompanyLocation location) {
Company company = companyService.findCompanyByIdx(companyIdx);
company = companyService.saveCompanyLocation(company, location);
if (company != null) {
return "success";
}
return "fail";
}

Do the below steps:
1) try to keep the jackson jar files in your classpath
2) eighter you have remove the datatype while sending ajax request i.e,
dataType : "json"
or you have to produce the application/json response as below
#RequestMapping(value = "/upload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
3) Check your DTO or Advert class properties which type should be matched with incoming request. i.e request params should match with DTO members both names and type.
These are possible ways to avoid your case.

Related

Spring Rest Controller POST request doesn't work with Ajax Json Array payload

I am getting 404 not found error while sending post request with json payload . At backend I am using spring rest controller .
Please find the code below .
#RequestMapping(value = "/api/testEnvironment/update", method = RequestMethod.POST , consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> updateEnvironment(#RequestParam("ids") String[] ids, #RequestParam("name") String name) {
System.out.println(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
And Jquery function for above rest controller :-
function testing(){
var a = [] ;
a.push('a');
a.push('b');
var b = '23';
var search = {
"ids" : a,
"name" : b
}
$.ajax({
type : "POST",
url : "api/testEnvironment/update",
contentType: "application/json",
data: JSON.stringify(search),
traditional: true,
success : function(data) {
},
error : function(e) {
}
});
}

How to send array of json objects to spring controller using ajax

I have converted all tables into json format using the below code:
var table2 = $('#yTable').tableToJSON();
alert(JSON.stringify(table2));
How do I send these three json arrays to spring controller? In spring controller I want these json array of objects as separate params:
[
{"Label":"A","Dimension":"0"},
{"Label":"B","Dimension":"10"},
{"Label":"C","Dimension":"20"},
{"Label":"D","Dimension":"30"},
{"Label":"E","Dimension":"40"}
]
[
{"Label":"1","Dimension":"0"},
{"Label":"2","Dimension":"10"},
{"Label":"3","Dimension":"20"},
{"Label":"4","Dimension":"30"},
{"Label":"5","Dimension":"40"}]
[
{"Label":"Floor1","Dimension":"0"},
{"Label":"Floor2","Dimension":"10"},
{"Label":"Floor3","Dimension":"20"},
{"Label":"Floor4","Dimension":"30"},
{"Label":"Floor5","Dimension":"40"}
]
ajax call
$.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url: "/bimspring/gridData",
data: JSON.stringify(postData),
success : function(response) {
// do something ...
},
error : function(e) {
alert('Error: ' + e);
}
});
Controller
#RequestMapping(value = "/gridData", method = RequestMethod.POST)
public #ResponseBody String getSearchUserProfiles(#RequestBody Search[] list) {
return null;
}

Send Json object parameter to Web Api controller in .netCore

This is Google API - Javascript code
var output = new Object();
output.PlaceID = place.place_id;
output.Longitude = place.geometry.location.lng();
output.Latitude = place.geometry.location.lat();
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
url: 'api/StorePlaces/Get',
type: 'POST',
data: { "value":output },
success: function (result) {
// Do something with the result
}
});
How to receive at the controller
// GET api/values/5
[HttpPost("{PlaceDetails}")]
public string Get(PlaceDetails value)
{
return "value";
}
In this case I get null value
I was unable to send the string , if I can send the Object as such, it is better.
This can be used as receiving object
public class PlaceDetails
{
public string PlaceID { get; set; }
public string Longitude { get; set; }
public string Latitude { get; set; }
}
There are multiple things wrong with your code, maybe consult a few beginner tutorials first?
First, you have to look at the object your are sending, it's very obvious!
You are sending
{
"value" : {
"PlaceID" : "",
"Longitude " : "",
"Latitude " : ""
}
}
Where the expected answer is
{
"PlaceID" : "",
"Longitude " : "",
"Latitude " : ""
}
So you have to use this in JavaScript:
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
url: 'api/StorePlaces/Get',
type: 'POST',
// do not wrap it in object with value property here!!!!
data: JSON.stringify(output),
success: function (result) {
// Do something with the result
}
});
Second, your Controller action (why the hell is it called Get when it's a post request?)... the [HttPost("{PlaceDetails}")] attribute is plain wrong.
This would expect a PlaceDetails parameter in the route. You don't such one! Just remove it. Also, the [FromBody] attribute is missing to tell it to deserialize the model from the http request body
[HttpPost]
public string Get([FromBody]PlaceDetails value)
{
return "value";
}

Passing in JSON array to spring MVC Controller

I am trying to pass a JSON array into spring MVC Controller like such:
var myList = new Array();
data._children.forEach( function (d) {
myList.push( {NAME: d.name, TYPE: d.TYPE, FDATE: d.FDATE } );
});
$.post("/ListRequest", {myList: myList});
The controller looks as such:
#RequestMapping(value="/ListRequest", method = RequestMethod.POST)
public void ListRequest(#RequestParam("myList") myList tempmyList )
{
System.out.println(tempmyList);
}
The class myList defined as such:
public class MyList {
private List<ListT> ListT;
public List<ListT> getListT() {
return ListT;
}
public void setListT(List<ListT> listT) {
ListT = listT;
}
}
ListT class:
public class ListT {
private String NAME;
private String TYPE;
private Long FDATE; ...
I keep getting this error:
HTTP Status 400 - Required myList parameter 'myList' is not present
Also tried this request:
$.ajax({
type: "post",
url: "ListRequest", //your valid url
contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me)
data: JSON.stringify(myList), //json object or array of json objects
success: function(result) {
//do nothing
},
error: function(e){
alert('failure');
}
but get this error: JBWEB000120: The request sent by the client was syntactically incorrect.
try to add this to you ajax call it should fix the unsupported response :
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
this is a full example of ajax call that is working for me :
$.ajax({
dataType : "json",
url : this.baseurl + "/dataList",
headers : {
'Accept' : 'application/json',
'Content-Type' : 'application/json'
},
data : JSON.stringify(params),
type : 'POST',
success : function(data) {
self.displayResults(data);
},
error : function(jqXHR,textStatus,errorThrown ){
showPopupError('Error','error : ' + textStatus, 'ok');
}
});
Even I was facing same problem.
My client request was right and generated proper json file.
but still i was getting same error.
I solved this error using #JsonIgnoreProperties(ignoreUnknown = true) in pojo class.
refer this link.
Spring MVC : The request sent by the client was syntactically incorrect
You can try
#RequestParam("myList") myList tempmyList
#Param myList tempmyList
in addition, class names must begin with a capital letter.

Getting parserror while sending JSON data to Webmethod

I am getting parseerror for my below ajax call, what can be wrong?
<script type="text/javascript" src="json.js"></script>
var contact1 = {
"id":"5",
"name": "fsdfsd"
};
var jsonString = "{\"JsData\":" + JSON.stringify(contact1) + "}";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/ReceiveData",
data: jsonString,
// data: DTO,
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(response,ajaxOptions, thrownError) {
alert("error:" + ajaxOptions);
}
});
My server side webmethod is
[System.Web.Services.WebMethod]
public static string ReceiveData(contact1 JsData)
{
//JsonTextParser parser = new JsonTextParser();
//JsonObject obj = parser.Parse(JsData);
//foreach (JsonObject field in obj as JsonObjectCollection)
//{
// string v = field.ToString();
//}
return "success";
}
public class contact1
{
public int id;
public string name;
}
I got the solution. I am using 2.0 framework, I forgot to add Ajax related references in my web.config. I added those manually, & it worked.