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
Related
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.
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'm sending an image from client side to my server which is implemented with Java in the Play Framework
$scope.uploadPicture = function() {
var image = $("#titlePicture img").attr("src");
$.ajax({
url: "api/uploadPicture",
type: "POST",
data: image,
async: false,
success: function (msg) {
// ...
},
cache: false,
contentType: false,
processData: false
});
}
In the request-header of my POST request I have the following Content-Type:
text/plain; charset=UTF-8
The POST itself contains, as seen above, the data from the image:
data:image/jpeg;base64,/9j/4AAQ[...]
The routing works fine. I do receive the below mentioned message in the success part of my ajax request:
public Result uploadPicture() {
// Store the image data under local folder ressources
return ok("File uploaded");
}
My question is on how I implement the commented line.
I am having a problem with passing a cookie while trying to make subsequent requests with AJAX to my Spring MVC controller.
For e.g. I have a /login endpoint to which I pass some JSON via POST method and it sets the cookie. I see the cookie in the firebug:
As you can see it is there. I am creating a cookie like this:
NewCookie cookie = new NewCookie(new Cookie(SECURITY_TICKET, encodedTicket, configKey, null), null, (int) TimeUnit.MINUTES.toSeconds(expireTime), expireTimeDate, false, false)
And setting it to HTTP headers:
httpHeaders.add(HttpHeaders.SET_COOKIE, cookie.toString());
Then these headers are being added to ResponseEntity like this:
ResponseEntity entity = new ResponseEntity<>(this.entity, this.httpHeaders, this.status)
And this response entity is returned. My conroller's methods are all REST based.
So then I am trying to call the other (/search) endpoint after successful login which functionality is expecting the cookie and it obviosly fails because for some reason cookie is not being passed back.
My AJAX calls looks like this:
$(function () {
$.ajax({
url: 'http://localhost:8080/dev-citigroup-citi/login',
type: 'POST',
dataType: 'json',
data: '{ "username": "client1", "password": "*******", "platform": "iOS", "UUID": "321321321", "application": "CitiReach", "applicationVersion": "1.0" }',
success: function (data, status, xhr) {
$.ajax({
url: 'http://localhost:8080/dev-citigroup-citi/search/eventattendee?q=*:*&start=0&rows=1&wt=json&indent=true',
type: 'GET',
xhrFields: { withCredentials:true },
success: function (data, status, xhr) {
console.log(data);
},
error: function (jqXHR) {
console.log(jqXHR);
}
});
},
error: function (jqXHR) {
console.log(jqXHR);
}
});
});
As I mentioned the /login is OK but the other call fails. I am adding xhrFields: { withCredentials:true } which should be including the cookie in the /search request but for some reason it is not.
I also have CORS being set up correctly:
Access-Control-Allow-Origin: http://localhost:63342
Access-Control-Allow-Credentials: true
http://localhost:63342 is the origin where the request comes from, it is configured in the CORS headers.
Any idea what might be wrong here?
I found the solution, so rather than having xhrFields: { withCredentials:true } on the method level, I've put it globaly:
$.ajaxSetup({
xhrFields: {
withCredentials: true
}
});
And cookie is passed now within the subsequent requests. No idea why it doesn't work on method level, maybe a bug in jquery...
jQuery version I was using: 2.1.3
Maybe this will help someone in future.
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 :)