I am sending a POST request:
var arr = { State: 'Moscow', Age: 25 };
var url = "/google/modifiedPolygon";
$.ajax({
url: url,
type: 'POST',
data: arr,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function() {
alert("msg");
}
});
And handling from backend as:
#RequestMapping(value="/modifiedPolygon",method = RequestMethod.POST,consumes = "application/json")
public void modifiedPolygon(#RequestBody JSONObject data, HttpServletRequest request, ModelMap model) {
System.out.println(data);
}
But I am getting following error:
org.springframework.http.converter.HttpMessageNotReadableException:
Could not read JSON: Unrecognized token 'State': was expecting
('true', 'false' or 'null')
It looks like State is a boolean type on the service side, But you are sending String value as State. So verify the datatype for State the service exepcting.
I have tried the following Java implementation and it seems working.
#RequestMapping(value="/modifiedPolygon",method = RequestMethod.POST,consumes = "application/json")
public ResponseEntity<JSONObject> modifiedPolygon(#RequestBody JSONObject data, HttpServletRequest request, ModelMap model) {
return new ResponseEntity<JSONObject>(data,HttpStatus.OK);
}
First test with POSTMAN or curl, if issue persists, try with this.
var arr = { state: 'Moscow', age: 25 };
var url = "/google/modifiedPolygon";
$.ajax({
url: url,
type: 'POST',
data: JSON.stringify(arr),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function() {
alert("msg");
}
});
And please enable the CORS filters.
Here are the working snapshot.
Add this dependency to pom.xml
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
Please find the java code changes here
https://github.com/supun/Shopping/blob/master/src/main/java/com/shopping/controller/MainController.java
You can use like this,
var arr = { state: 'Moscow', age: 25 };
var url = "/google/modifiedPolygon";
$.ajax({
url: url,
type: 'POST',
data: { "dataValue": JSON.stringify(arr)},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function() {
alert("msg");
}
});
now, you can get "dataValue" in backEnd from body param.
Related
here is my code,I am using angular and spring mvc . Please suggest me the way
vm.upload= function(state_cd){
fd= new FormData();
fd.append("mst.distCd", dist_cd);
call(fd);
});
}
function call(fd){
$http({
type: "POST",
url: "./WQF00069/update.app",
data: fd,
processData: false,
headers: { 'Content-Type': undefined},
transformRequest: angular.identity,
cache: false,
timeout: 600000,
}).success(function(data) {
Flash.create('info', ' Update Success Fully ', 'large-text');
}).error(function(response){
console.dir(response);
Flash.create('danger','There is a Problem.Contact With Administrator', 'large-text');
});
}
After send to my controller get get 415 error
I have a form which I convert into an object. I wanna pass that object onto the server, a GET ajax request works fine but the object is empty in the java method, then I do the very same request but a POST request and it says error 404. Not sure what I'm doing wrong or what is, followed many examples, but neither of them seem to work.
GET REQUEST
(Ajax call)
$.ajax({
type: "GET",
url: "/pp/portal/" + businessId64 + "/saveMedicalQuestionnaire",
contentType: 'application/json',
dataType: 'json',
data: { medicalHistoryDTO : medicalHistoryDTO },
success: function(data) {
console.log(data);
}
});
(Object medicalHistoryDTO)
(Java Method)
#RequestMapping(value="/*/saveMedicalQuestionnaire", method = RequestMethod.GET)
public #ResponseBody String postEditMedical(MedicalHistoryDTO medicalHistoryDTO)
{
System.out.println("COMMON CONTROLLER POSTEDITMEDICAL SAVE MEDICAL QUESTIONNAIRE");
System.out.println(medicalHistoryDTO);
return "WORKING FINE";
}
(Eclipse console)
COMMON CONTROLLER POSTEDITMEDICAL SAVE MEDICAL QUESTIONNAIRE
MedicalHistoryDTO [list=null, medicalHistorySignature=null]
(Browser console)
POST REQUEST
(Ajax call)
$.ajax({
type: "POST",
url: "/pp/portal/" + businessId64 + "/saveMedicalQuestionnaire",
contentType: 'application/json',
dataType: 'json',
data: { medicalHistoryDTO : medicalHistoryDTO },
success: function(data) {
console.log(data);
}
});
(Java Method)
#RequestMapping(value="/*/saveMedicalQuestionnaire", method = RequestMethod.POST)
public #ResponseBody String postEditMedical(MedicalHistoryDTO medicalHistoryDTO)
{
System.out.println("COMMON CONTROLLER POSTEDITMEDICAL SAVE MEDICAL QUESTIONNAIRE");
System.out.println(medicalHistoryDTO);
return "WORKING FINE";
}
(Browser console)
Keep using POST and to recieve you need to use #RequestBody tag
public #ResponseBody String postEditMedical(#RequestBody MedicalHistoryDTO medicalHistoryDTO)
You can see a working example from my code to https://github.com/shakeelabbas1/webservice/blob/master/src/main/java/com/service/controller/ServiceRequestController.java
Update:
I also see data: { medicalHistoryDTO : medicalHistoryDTO }
Replace it with data: medicalHistoryDTO
try to specify path more strictly
#RequestMapping(value="/{id}/saveMedicalQuestionnair", , method = RequestMethod.POST)
public #ResponseBody
String postEditMedical(MedicalHistoryDTO medicalHistoryDTO, #PathVariable("id") int id)
I need to pass a json string from my jsp page to spring mvc controller.My JSON String and its passing using ajax call is shown below
var datejson = '{'
+'"startmonth" : smonth,'
+'"startday" : sday,'
+'"endmonth" : emonth,'
+'"endday" : eday'
+'}';
alert("json created");
//var jsonfile={json:JSON.stringify(datejson)};
$.ajax({
type: 'POST',
contentType : 'application/json; charset=utf-8',
dataType: 'json',
url: "/pms/season/json/",
data: JSON.stringify(datejson),
success: function(data) {
alert(data.startmonth + " " + data.endmonth);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
Every time my error function alerts.So how to pass it?
The code to recieve json in Controller class is shown below
#RequestMapping(value = "json", method = RequestMethod.POST)
public void validationDate( #RequestParam ("json") String datejson)
{
//System.out.println("JSON TEST");
System.out.println("JSON CONTENTS ARE::::::"+ datejson );
}
I am new to jquery.Any help will be highly appreciable...
I have the following controller:
#RequestMapping(value = { "/member/uploadExternalImage",
"/member/uploadExternalImage" }, method = RequestMethod.POST)
public String handleFileUpload(#RequestParam("url") String url,
Principal principal) throws IOException {
File file = restTemplate.getForObject("url", File.class);
file.toString();
return null;
}
And I have the following ajax:
$.ajax({
url: 'uploadExternalImage', //Server script to process data
type: 'POST',
success: function () {
},
complete:function(){
$.fancybox.hideLoading();
},
// Form data
data: {url: files[0].link},
cache: false,
contentType: false,
processData: false
});
in spring log I see that
org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'url' is not present
if I change ajax method with GET:
$.ajax({
url: 'uploadExternalImage?url=123', //Server script to process data
type: 'POST',
success: function () {
},
complete:function(){
$.fancybox.hideLoading();
},
error: function (data) {
},
cache: false,
contentType: false,
processData: false
});
it works fine
How does to configure spring correctly?
Http POST is capable of being used for request parameters on request body. But you are trying to use it on a different way.
Try this:
$.ajax({
type: 'POST',
url: "uploadExternalImage?url=BLABLA",
data: text,
success: function (data) {
//
}
});
If you want it on request body then use #RequestBody
I have the restful webservices call from the Jquery ajax and getting the response in json object.
Jquery HTML:
$.ajax({
url: "mcrs/object/api/Lighting",
type: "POST",
traditional: true,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
async: "false",
data:JSON.stringify(postdata),
success: function (ResData) {
},
error: function (error, data) {
console.log(error);
}
});
}
});
And writing the response object for the restful webservices in java
#POST
#Path("api/{subsystem}")
#Produces("application/json")
public Response changeStatus(#PathParam("subsystem") String subsystem,
/*#FormParam("result")*/ String result) {
}
I got the response below and which is correct
changeStatus:88 - Reponse OutboundJaxrsResponse{status=200, reason=OK, hasEntity=true, closed=false, buffered=false}
Depending upon the reponse need to update the status whether the value is on/off in the label tag.
str = ' Status : ' + '' + onoffStat + '';
How can I achieve this in ajax and want to have the refreshing the div tag for every 2 seconds.
Please help me.
You will have to use Javascript polling. Try out something like this:
function ajaxPoll(){
$.ajax({
url: "mcrs/object/api/Lighting",
type: "POST",
traditional: true,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
async: "false",
data:JSON.stringify(postdata),
success: function (ResData) {
tag.str = 'Status : ' + '' + ResData.status + '';
},
error: function (error, data) {
console.log(error);
}
});
}
});
}
setInterval(ajaxPoll, 2000);
Hope you sort it out :)