ajax with spring mvc always getting error - java

Every request ajax getting an error.
Ajax function:
function doAjax() {
var inputText = $("#info").val();
$.ajax({
type: 'POST',
url: 'ajax',
// data: ({text: inputText}),
dataType: 'json',
data: 'text='+inputText,
success: function (response) {
$("#result_info").text(response);
}
error: function (e) {
alert('error' + e.responseText);
}
});
}
Java Controller
#RequestMapping(value = {"/ajax"}, method = RequestMethod.POST)
public #ResponseBody String showText(#RequestParam String text) {
System.out.println(text);
String returnText = "empty";
if (!text.isEmpty()) {
returnText = " response: " + text;
}
return returnText;
}
Besides this question could you tell what is the difference between in ajax query
data: ({text: inputText}),
data: 'text='+inputText,

In this particular case it's better to change dataType to html instead of json. I solved it.

Related

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

Pass model and a string using ajax to Spring MVC

Hi I need to pass the full model and one string from html to Spring controller using AJAX. I use the below code snippet but it doesn't work.
var str = $("#resourceManagement").serialize();
var agreementId = ${agreementId};
var tempCnltName=$modal.find("input[data-type='cnltName']").val();
$.ajax({
type:"POST",
data: {str, tempCnltName},
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline",
async: false,
dataType: "json",
success: function (data, status, xhr) {
message = data.errorMsg;
},
error: function () {
}
});
The problem is that if I pass model alone (str) or string alone (tempCnltName) I can get it in controller but I cannot get both together.
My controller is as below:
#RequestMapping(value = "/app/agreement/checkDuplicateConsultantOnline", method = RequestMethod.POST)
public #ResponseBody AjaxResponse checkDuplicateConsultantOnline(
#ModelAttribute("consultantBidModel") ConsultantBidModel model,
#RequestParam(value = "tempCnltName", required = false) String cnltName,
HttpServletRequest request,
HttpSession session) throws Exception {
final Set<String> allCnltNames = new HashSet<>();
String errMessage = "";
if (model.getLeadingCnltName() != null) {
allCnltNames.add(model.getLeadingCnltName().toLowerCase());
}
if (model.getJointVentureConsultants() != null) {
for (ConsultantBidListItem entry : model.getJointVentureConsultants()) {
if (!allCnltNames.add(entry.getCnltName().toLowerCase())) {
errMessage = "Each consultant can only appear once.";
}
}
}
if (model.getSubConsultants() != null) {
for (ConsultantBidListItem entry : model.getSubConsultants()) {
if (!allCnltNames.add(entry.getCnltName().toLowerCase())) {
errMessage = "Each consultant can only appear once.";
}
}
}
AjaxResponse response = new AjaxResponse();
if (errMessage != null) {
response.setSuccess(true);
response.setResponseObject(errMessage);
response.setErrorMsg(errMessage);
}
return response;
}
On the server side, you're already prepared to receive both the model (with #ModelAttribute) and an additional URL parameter (with #RequestParam)
On the client, append the URL parameter to the URL. Assuming that str is your model and tempCnltName is your string to submit to the server:
$.ajax({
type:"POST",
data: str,
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline?tempCnltName=" + tempCnltName,
...
try
var strVal = $("#resourceManagement").serialize();
var agreementId = ${agreementId};
var tempCnltNameVal=$modal.find("input[data-type='cnltName']").val();
$.ajax({
type:"POST",
data: {str: strVal, tempCnltName: tempCnltNameVal},
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline",
async: false,
dataType: "json",
success: function (data, status, xhr) {
message = data.errorMsg;
},
error: function () {
}
});
Probably the malformed json is causing trouble
Another way of doing the above, add the string to model:
var strVal = "consulName=" + tempCnltName + "&";strVal = strVal + $("#resourceManagement").serialize();
The model can then have a new parameter consulName and we can get the value in Controller.

How to post a json array to java servlet with jquery

I'm currently developing spring mvc application and I need to post JSON array.
When I access request.getParameter("paramValue") to fetch the param attibute, but it returning a null value,
Here is my front-end code:
$.ajax(url, {
async: true,
type: 'post',
contentType: 'application/json',
data: JSON.stringify({
"test":"test value"
})
}).done(function (response) {
console.log(data);
}).fail(function (xhr) {
console.log("request failed");
console.log(xhr);
});
Here is my server-side code:
#RequestMapping(value = "/Products", method = RequestMethod.POST)
public void saveProducts(HttpServletRequest req, HttpServletResponse res) throws Exception {
System.out.println(req.getContentType());
System.out.println(req.getContentLength());
System.out.println(req.getContextPath());
System.out.println(req.getParameterValues("test"));
System.out.println(req.getMethod());
StringBuilder buffer = new StringBuilder();
BufferedReader reader = req.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String data = buffer.toString();
System.out.println(data);
System.out.println(req.getParameter("test"));
}
The output is:
application/json
22
null
POST
{"test" : "Test DAta"}
null
I can't figure out whats going on, please help me.
remove this line in you ajax function
contentType: 'application/json',
and replace this line
data: JSON.stringify({
"test":"test value"
})
with
data: {
"test":"test value"
}
and also you can use
req.getParameter("test")
instead
req.getParameterValues("test")
You can by using this :
var data ={id: 1, name :'test'}
$.ajax(url, {
async: true,
type: 'post',
contentType: 'application/json',
data: data
}).done(function (response) {
console.log(data);
}).fail(function (xhr) {
console.log("request failed");
console.log(xhr);
});
and in server side
create a pojo :
public class Product{
private long id;
private String name;
// getters and setters
add library jackson .
add this method in your controller:
#RequestMapping(value = "/Products", method = RequestMethod.POST)
public RepsoneEntity<? >saveProducts(#requestBody Product pr){
LOG.debug(pr.toString());
return new reRepsoneEntity<Product>(pr,HttpStatus.ACCEPTED);
}
i finally fixed it several annotation and changing the the return type of server side method,
#RequestMapping(value = "/Products", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public ResponseEntity<?> saveProducts(#RequestParam(value = "data") String brand) {
return ResponseEntity.ok(brand);
}</code>
front end
$.ajax(url, {
async: true,
type: "POST",
data: {"data" : JSON.stringify({"Brand" : "Test Brand"})}
}).done(function (response) {
console.log(response);
}).fail(function (xhr) {
console.log("request failed");
console.log(xhr);
});
and i used org.json to access json objects parsed as text, gson to deal with POJOs
and now it works :)

returning error response in jquery

I am trying to call a controller from jquery.Here every thing works fine,but in ajax it shows error alert. What is going wrong.
$.ajax({
type: 'POST',
url:'<%=request.getContextPath()%>/billing',
data: ({caseId: caseId, noteID : noteID}),
cache: false,
success: function(data){
alert("Success");
},
error: function(xhr, textStatus, error){
alert("Error occured.");
}
});
My controller
#RequestMapping(value = "/billing", method = RequestMethod.POST)
public String Billing(#RequestParam Long caseId,
#RequestParam Long noteID, HttpServletRequest request) throws Exception {
try{
----Some data base updation---
logger.debug("success ");
return "success";
} catch (Exception e) {
logger.error(e,e);
throw e;
}}
Please help me in this.
//you have to left content type to send the server side ,please define content type..
$.ajax({
type: "POST",
url: '#Url.Action("PerTGradeMastEdit", "Master")',
data: "{'Request':'" + request + "'}",
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response != null) {
var strResponse = response;
var ProgramData = strResponse.split("/");
// response = ProgramData[0];programId
$('#txtPerGrade').val(ProgramData[0]);
$('#txtDesc').val(ProgramData[1]);
}
},
failure: function (msg) {
alert(msg);
window.location.href = '#Url.Action("INDEX", "AUTHORIZE")';
}
});`enter code here`

How to pass json string from jsp page to Spring mvc controller?

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...

Categories

Resources