Ajax response arrives empty from spring controller, even if it succeeded - java

I received empty data from spring controller, even if it returned data the ajax success function received it empty. I tried to return string directly from controller like this:
#ResponseBody
#RequestMapping(value = "/test", method = RequestMethod.POST)
public String test(#RequestParam("posImsi") String posImsi,#RequestParam("posMsisdn") String posMsisdn){
return "success";
}
and the ajax is:
$.ajax({
url : "test",
type : "POST",
data : formData,
beforeSend : function(){
$("#overlay").show();
},
success : function(ajaxResult){
console.log(ajaxResult);
},
complete : function(status) {
},
error : function(jqXHR, status, errorThrown) {
alert(jqXHR);
alert(status);
alert(errorThrown);
}
});

The problem is solved by using the XMLHttpRequest object to do ajax request, I really don't know what is the difference but here is what I used:
var x = new XMLHttpRequest();
x.open("POST","test",true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
x.send(formData);
x.onload = function () {
console.log(this.responseText);
};
for more information about XMLHttpRequest object: http://www.w3schools.com/xml/dom_http.asp

Related

Read return value of $.ajax POST Method gives just return value Object object

I want to use following ajax method to call a java function (I use Spring Boot and Hibernate) and read the return value afterwards. The function '/myFunction' is correctly called and the return value is a string and is correctly logged in the java function. But I don't get it, how I can use the return message from the java-method in the success-part afterwards. (notifyUser is a little function(title, message) that shows a notification to an user, this function works correctly) By now, notifyUser just post Error [object Object]
$.ajax({
type : 'POST',
contentType : 'application/json',
url : '/myFunction',
data : JSON.stringify({
fooM,
fooO,
fooS
}),
dataType : 'json',
cache : false,
timeout : 600000,
success : function(data) {
notifyUser('Info', data);
},
error : function(e) {
notifyUser('Error', e);
}
});
#RestController
#Secured({ "ROLE_USER", "ROLE_ADMIN" })
public class MyController {
#RequestMapping(value = "/myFunction", method = RequestMethod.POST)
public String myFunction(#RequestBody MyRequestClass request ) {
String return_string = "Check if return value works " + request.getFooM() + request.getFooO() +request.getFooS();
log.debug(return_string)
//Up to this step, everything works
return return_string;
}
}
What do I have to change, that I'm able to get the return value of the called function '/myFunction' in the success part and send the string to notifyUser?
Thank you for your answers.
Phil

SyntaxError: Unexpected token s in JSON at position 0 at JSON.parse + angularjs

I am working with springmvc and angularjs. I'm trying to send the String response from springmvc controller to the angular controller, but facing the below error message shown on the browser console and the response which returned from springmvc is not getting printed in the angularjs side.
ERROR:
SyntaxError: Unexpected token s in JSON at position 0
at JSON.parse ()
Sample code:
js:
myApp.controller('myTestCtrl', function ($rootScope, $scope,MyService) {
$sco[e.submitInfo = function(){
var data = new FormData();
var allInfo =
{
'name': $scope.name,
'id': $scope.id,
'product': $scope.product,
'message':$scope.message
}
//files to be attached if exists
for (var i in $scope.filesAttached) {
var file = $scope.filesToAttach[i]._file;
data.append("file", file);
}
MyService.sendAllInfo(data).then(
function (response) {
if (response === "") {
alert("success");
//logic
}else{
alert("in else part " + response);
}},
function (errResponse) {
console.log("Error while retrieving response " + errResponse);
});
};
});
}});
MyService:
myService.sendAllInfo = function (data) {
var deferred = $q.defer();
var repUrl = myURL + '/myController/allInfo.form';
var config = {
headers: {'Content-Type': undefined},
transformRequest: []
}
$http.post(repUrl,data,config)
.then(
function (response) {
alert("response json in service: "+ response);
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while getting response.data'+ errResponse);
deferred.reject(errResponse);
}
);
return deferred.promise;
};
Spring mvc:
#RequestMapping(value = "/allInfo", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE)
public #ResponseBody
String allInfoData(#RequestParam("data") String data,#RequestParam("file") List<MultipartFile> files){
//logic
return "success";
}
In my above spring controller code, i'm returning success string to angularjs controller, but in the browser the below error is displayed.
SyntaxError: Unexpected token s in JSON at position 0
at JSON.parse ()
Note: Above is only the sample code , it is perfectly hitting the spring controller and issue is only while catching the response from spring controller to angular controller.
I tried to change produces=MediaType.TEXT_PLAIN_VALUE to produces={"application/json"} but still it is showing the same error.
To avoid parsing the string, use transformResponse: angular.identity:
myService.sendAllInfo = function (data) {
̶ ̶v̶a̶r̶ ̶d̶e̶f̶e̶r̶r̶e̶d̶ ̶=̶ ̶$̶q̶.̶d̶e̶f̶e̶r̶(̶)̶;̶
var repUrl = myURL + '/myController/allInfo.form';
var config = {
headers: {'Content-Type': undefined},
transformRequest: [],
//IMPORTANT
transformResponse: angular.identity
}
var promise = $http.post(repUrl,data,config)
.then(
function (response) {
alert("response json in service: "+ response);
return response.data;
},
function(errResponse){
console.error('Error while getting response.data'+ errResponse);
throw errResponse;
}
);
return promise;
};
Also avoid using the deferred Anti-Pattern.
In the response there are some values which are simple text not String so You're asking it to parse the JSON text something (not "something"). That's invalid JSON, strings must be in double quotes.
If you want an equivalent to your first example:
var s = '"something"';
var result = JSON.parse(s);
The best solution is use responseType: "text" as "json" it will woke

Posting a JSON to a Spring Controller

I'm learning to pass a JSON object through ajax to a Spring Controller.
Found an article, that seems to explain how its done: http://hmkcode.com/spring-mvc-json-json-to-java/
From that point i added a #RequestMapping to the Controller:
#RequestMapping(value = "/get-user-list", method = RequestMethod.POST)
public #ResponseBody String testPost(#RequestBody ResourceNumberJson resourceNumberDtoJson) {
System.out.println(">>>>>>>>>>>>>>>>>>>>>> I AM CALLED");
return "111";
}
Then i'm forming my ajax post:
var json = {
"login" : "login",
"resource_number" : "111",
"identifier" : "1111",
"registrator_number" : "11111111111111"
};
console.log(JSON.stringify(json));
$.ajax({
type : "POST",
url : "/get-user-list",
dataType : "text",
data : JSON.stringify(json),
contentType : 'application/json; charset=utf-8',
mimeType: 'application/json',
success: function(data) {
alert(data.id + " " + data.name);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
which is runned from "get-user-list" page.
When i'm trying to run this, i recieve a HTTP 415 error. Spring 4, Jackson 2.4
Cant understand what i'm doing wrong.
HTTP 415 means, that the media type is not supported.
Try changing your #RequestMapping annotation to
#RequestMapping(value = "/get-user-list",
method = RequestMethod.POST,
consumes="application/json")
You should also consider testing your REST-service with a client like RESTClient, Postman or even cURL to make sure it is working correctly before you start implementing the jQuery client.

Why does #ResponseBody on a void method with Spring MVC show no element found in the Firefox console?

I have a Spring MVC controller that I am calling via JQuery.ajax.
The mapping in the controller is:
#RequestMapping(value = "/remove", method = RequestMethod.POST)
#ResponseBody
public void remove(#RequestParam("value1") String value1,
#RequestParam("value2") String value2)
{
// do stuff
}
The ajax call is:
$.ajax({
url: '/appserver/model/remove',
data: { value1: value1, value2: value2 },
type: 'POST',
traditional: true,
success: function() {
// do something on success
},
error: function(jqXHR, textStatus, errorThrown) {
// do something on error
}
});
The POST call completes successfully with HTTP status 200. However, in the Firefox console the following is output:
no element found ... myscript.js:1
If I change my controller to return a boolean then this error disappears. However, according to this question having #ResponseBody on a method with void return type is valid.
Is there anything I can change to remove this message?
As described in the JQuery Bugs and in Firefox Bug, it is a Firefox problem that occurs when response entity body is null.
To fix it, you have to return such a ResponseEntity in your Controller method.
Try to add dataType: 'text' in your request:
$.ajax({
url: '/appserver/model/remove',
data: { value1: value1, value2: value2 },
type: 'POST',
traditional: true,
dataType: 'text',
success: function() {
// do something on success
},
error: function(jqXHR, textStatus, errorThrown) {
// do something on error
}
});
and modify your Controller to return a ResponseEntity with a String as first parameter
#RequestMapping(value = "/remove", method = RequestMethod.POST)
public ResponseEntity<String> remove(#RequestParam("value1") String value1,
#RequestParam("value2") String value2)
{
// do stuff
return new ResponseEntity<String>("OK!!!",HttpStatus.NO_CONTENT);
}

can not able to call spring controller using ajax

I am trying to call a spring controller using ajax, but can not able to go to the controller. I am getting Error 405 Request method 'POST' not supported error. I am keeping my code here please give suggestion to come over it
this is my ajax code calling controller from jsp page, here i am getting the anchor attribute value.
basic.jsp
function organizationData(anchor) {
var value = anchor.getAttribute('value');
$.ajax({
url : "manageOrganization",
method : "GET",
dataType: "json",
contentType: 'application/json',
data: {organizationId : value },
success : function(response) {
alert(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
}
controller
#RequestMapping(value="/manageOrganization", method = RequestMethod.GET)
public String organizationData(#RequestParam String organizationId) {
return organizationId+" associated";
}
here i should get the string to the jsp as a ajax response, but i am getting the error message. Any body can help me.
Regards Sree
For json response you need to add #ResponseBody annotation to your controller method.
You need to use type:"GET" not method:"GET" try it like,
$.ajax({
url : "manageOrganization",
type : "GET", // its type not method
dataType: "json",
.....
Read jQuery.ajax()
Also check that you are returning a json or not.
Your controller is returning String which may be resolved into some other jsp file IF you have configured viewResolver in spring configuration file. Try adding #ResponseBody like this:
#RequestMapping(value="/manageOrganization", method = RequestMethod.GET)
public #ResponseBody
String organizationData(#RequestParam String organizationId) {
return organizationId+" associated";
}

Categories

Resources