I am trying to bind my form with modelattribute in controller throught ajax call but i didnt get the values in bean e.g all values of bean are null
I printed the form data in alert() its showing me correct data but in controller its showing me null
This is my ajax call and console.log() print whatever i want but in controller i am not getting my data.
Ajax call ::
function viewBugReport(data) {
var formdata=$("#getAppForm_"+data).serialize();
console.log(formdata);
$.ajax({
url : 'displaybugreport.html',
data :formdata,
processData : false,
contentType : false,
type : 'POST',
success : function(data) {
alert(data);
}
});
}
Controller code ::
#ResponseBody
#RequestMapping(value = "/displaybugreport.html")
public String viewBugReport(#ModelAttribute BugReportBean1 bugreportbean,
HttpSession session) {
String ResultMessage = "something went wrong!!";
String adminId = "X";
System.out.println(bugreportbean);
try {
AdminBean adminBean = (AdminBean) httpSession.getAttribute(SESSION_KEY_ADMIN);
adminId = adminBean.getUserId().trim();
ResultMessage = bugReportService.submitBugReport(bugreportbean);
} catch (Exception e) {
logger.debug("GADG:" + adminId
+ " :: Exception occured :: viewBugReort POST method :: BugReportController class");
e.printStackTrace();
}
return ResultMessage;
}
As I can't see the full controller and you haven't mentioned any HTTP method in your desired endpoint, you can try like this:
#RequestMapping(value = "/displaybugreport.html", method = RequestMethod.POST)
Related
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
i am attempting to call Spring controller method from JQuery ajax call, but its not navigate to corresponding view.
First i am verifying login details by calling authenticateLogin() Spring controller function from ajax call, after successful validate i need to forward the request to corresponding view page, i have tried with below code but its not navigate to another page.
Javascript function:
function authenticatePricingCalcLogin() {
var login = {
userName : $("#username").val(),
password : $("#password").val()
};
$.ajax({type: "POST",
url: CONTEXT_PATH+"authenticateLogin",
data:JSON.stringify(login),
contentType : 'application/json; charset=utf-8',
dataType : 'json',
success: function (response) {
if (response != null) {
if (response.errorMsg != null && response.errorMsg != "") { // Login Error
alert(response.errorMsg);
} else {
// Here i need to call spring controller method and to redirect to another page
// I have tried
$.ajax({type: "GET",
url: CONTEXT_PATH+"navigateMainPage",
data:JSON.stringify(loginDO),
contentType : 'application/json; charset=utf-8',
dataType : 'json'
});
}
}
}
});
}
AuthController.java
#RequestMapping(value = "/authenticateLogin", method = RequestMethod.POST)
public #ResponseBody LoginDO authenticateLogin(#RequestBody Login login){
return authService.authenticateLogin(loginDO);
}
#RequestMapping(value = "/navigateMainPage", method = RequestMethod.GET)
public String navigateMainPage(#ModelAttribute("loginDO") Login login,HttpServletRequest request, Model model) {
try {
// Need to set User Name in session variable
} catch (Exception e) {
}
return "auth/mainPage";
}
Please add / in your path
url: CONTEXT_PATH+"/authenticateLogin",
Hi friend I don't have Comment authority so just answering your question.just comment data part if it is GET Type request and remove it form java side #ModelAttribute("loginDO") Login login, Otherwise just make it POST and check any CSRF token is there or not for safe side.
I am getting error ""Required UsernameSearch parameter 'username' is not present" when sending data using ajax with Spring and Thymeleaf. My script is as shown below
<script>
$(document).ready(function() {
$("#opusername").keyup(function() {
var username = $('#opusername').text();
$.ajax({
type : "POST",
contentType : "application/json",
url : "/create/check-username-availability",
data : {"username" : username},
dataType : 'json',
timeout : 100000,
success : function(data) {
console.log("SUCCESS: ", data);
},
error : function(e) {
console.log("ERROR: ", e);
},
done : function(e) {
console.log("DONE");
}
});
});
});
My controller has this method which should receive the string and return a value to indicate whether the username is available or not.
#RequestMapping(value = "/create/check-username-availability", method = RequestMethod.POST)
#ResponseBody
public String checkUsernameAvailability(#RequestParam("username") UsernameSearch username) {
logger.info("Checking username availability for username = " + username.getUsername());
return "true";
}
This is the object I create which contains the username String. I have done this after following tutorials and answers here but nothing seems to work.
public class UsernameSearch {
String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
This is the error when debugging
error:"Bad Request"
exception:"org.springframework.web.bind.MissingServletRequestParameterException"
message:"Required UsernameSearch parameter 'username' is not present"
path:"/create/check-username-availability"
status:400
timestamp:1489942516434
I also wanted to ask how to consume the result from the spring method. Is it possible to get a boolean value?
Change #RequestParam to #RequestBody. Request param != body of the request.
The 400 HTTP error means that the the request is malformed. In your case, the controller expects that the url will have a "username" parameter. Therefore you can either change the ajax call, to send the username as the request parameter, i.e. by attaching "?username=fooBar" to the url you're perfoming POST request and change the controller method signature to accept #RequestParam("username") String username, or change the annotation on the controller parameter to #RequestBody, which tells the controller that the data will be sent as an object in the body of the request.
function ajax:
var data = {
username: $('#opusername').text()
};
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: "/create/check-username-availability",
data: JSON.stringify(data), // Note it is important
success: function (result) {
// do whatever you want with data
}
});
and in your java method
#RequestMapping(value = "/create/check-username-availability", method = RequestMethod.POST)
#ResponseBody
public String checkUsernameAvailability(#RequestBody UsernameSearch username) {
logger.info("Checking username availability for username = " + username.getUsername());
return "true";
}
Don't send your data as string!
Do the following:
data : {"username" : username},
I think you are getting caught up with the various levels all labeled as username. As your server is written now, it is expecting a parameter which is identified as username to be of type UsernameSearch which is an object with a single property of username. To be explicit, you are expecting the sent body (which is an object) to have a property of username where the value is an object which also has a property called username. So the server is expecting
{
'username': {
'username': 'search value'
}
}
What you are sending is an object with a property of 'username' but a value of string:
{
'username': 'search value'
}
The answer is to be consistent. If you think your search criteria will become more than the one field, then update your client, if not, then change the server to accept a string rather than an object.
Update:
Also, you have #RequestParam but you should use #RequestBody.
I have created a spring controller and a jsp page. In jsp page I am using jquery ajax call to hit the controller. Now, this controller returns a json response as string. Now on based of json response in success method, I want to call a next controller call which will return a ModelAndView jsp page. How can I do this. Below is my code:
JSP Jquery ajax call:
$(document).ready(function(){
$("#submitButton").click(function(e){
var formData = getFormData();
if(formData!=false){
$.ajax({
type: 'POST',
'url': 'http://localhost:8080/Test_ReportingUI/fieldMappingNext.htm',
data: {jsonData: JSON.stringify(formData)},
dataType: 'json',
success: function(response){
try{
var strResponse=jQuery.parseJSON(response);
}catch(err){}
if(response.status=='ok')
{
alert ("okokokokokokokokok");
//I am successfully reaching till here.
//But in case of this alert box I want to call a
//controller which will return ModelAndView and
//should open a corresponding ModelAndView jsp page.
//something like:
/*
$.ajax({
type: 'GET',
'url': 'http://localhost:8080/Test_ReportingUI/abcxyz.htm',
)};
*/
}
else
{
alert("ERROR!!");
}
},
timeout: 10000,
error: function(xhr, status, err){
if(response.status=='timeout')
{
alert('Request time has been out','');
}
console.log(status,err);
}
}); }
});
});
Controller class methods:
#RequestMapping (value="fieldMappingNext.htm", method=RequestMethod.POST)
#ResponseBody String addFieldMappingNext(#RequestParam String jsonData)
{
String customerID =null;
String objectID = null;
String syncFieldName = null;
String optMapping = null;
JSONObject jsonResponse = new JSONObject();
try{
JSONObject requestedJSONObject = new JSONObject(jsonData);
customerID = requestedJSONObject.getString("customerID");
objectID = requestedJSONObject.getString("objectID");
syncFieldName = requestedJSONObject.getString("syncFieldName");
optMapping = requestedJSONObject.getString("optMapping");
}catch(Exception exex){
exex.printStackTrace();
}
if(optMapping.equalsIgnoreCase("direct")){
long metadataID=rwCustomerService.getMetaDataID(customerID,objectID);
List<RWFieldDetail> list=rwCustomerService.getFieldDetailNames(metadataID);
request.setAttribute("customerID", customerID);
request.setAttribute("objectID", objectID);
request.setAttribute("optMapping", optMapping);
request.setAttribute("syncFieldName", syncFieldName);
request.setAttribute("fieldNames", list);
try {
jsonResponse.put("status", "ok");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jsonResponse.toString();
}
Second Controller method that I want to call from jquery success method:
#RequestMapping (value="abcxyz.htm", method=RequestMethod.GET)
ModelAndView fieldMapping(){
ModelAndView modelAndView=new ModelAndView("FieldMappingMainScreenNext");
return modelAndView;
}
How do I do this.
Since the second handler method returns ModelAndView, you should redirect from the success callback:
...
success: function(response) {
window.location.replace(response.url);
}
...
In your Java code you can use something like:
Map<String, String> map = new HashMap<String, String>();
if(condition1){
map.put("url","url1.html");
}
if(condition2){
map.put("url","url2.html");
}
Convert it to a JSON string and revert it back. Afterwards, in the jquery portion you'll get the response:
success:function(jsonStr){
var obj = JSON.parse(jsonStr);
var url = obj.url;
}
That is how you can get the url. If you want to load an other page or create an ajax call then you can do it.
I have a Spring MVC controller being called by AJAX and returns JSON. If the call succeeds without error, I am returning a string message with the key "message". Likewise, if an exception is caught, I return a string error also with the key "message". I also return a HTTP error response.
In my Javascript, I output this "message" in an alert. The alert displays the message in the event of a successful call. If the call is unsuccessful, I get a Javascript error that "data is undefined".
Why is "data" accessible when successful but not when the call fails, and what correction do I need to make this work?
I am a newbie to AJAX calls with Spring so any general feedback/critique of my solution below is welcome and appreciated.
N.B. The alerts in the Javascript and the messages themselves are dummy implementations until I correctly provide user feedback by modifying the DOM.
The Controller
#RequestMapping(value = "/getMovieData", method = RequestMethod.POST, produces = "application/json")
#ResponseBody
public Map<String, Object> getMovieData(#RequestBody Map<String, Object> json, HttpServletResponse response) {
String movieId = json.get("id").toString();
Map<String, Object> rval = new HashMap<String, Object>();
try {
Movie movie = movieService.getMovieData(movieId);
rval.put("message", "You have succeeded");
rval.put("movie", movie);
} catch (Exception e) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
rval.put("message", "You have an error - " + e.getMessage());
}
return rval;
}
The Javascipt
function getMovieData(data) {
var request = $.ajax({
type : 'POST',
url : '<c:url value="/getMovieData" />',
dataType : "json",
contentType : "application/json; charset=utf-8",
data : data,
});
request.done(function(data) {
alert("Success: " + data.message);
populateMovieFields(data.movie);
});
request.fail(function(xhr, status, error, data) {
alert("status: " + status);
alert("error: " + error);
alert("Fail: " + data.message);
});
}
The JSON response is available inside the jqXHR object passed as the first parameter.
request.fail(function(jqXHR, textStatus, errorThrown) {
alert("Fail: " + jqXHR.responseJSON.message);
});